Consider this code:
constexpr size_t size = 32;
constexpr size_t count = 8;
using WordCode = unsigned;
template<typename T>
int CmpHashArray(const T *l,const T *r)
{
auto * l1 = reinterpret_cast<const __int32*>(l);
auto * r1 = reinterpret_cast<const __int32*>(r);
if(*l1 == *r1)
return 0;
if(*l1 < *r1)
return -1;
return 1;
}
int CmpHashArray2(const WordCode *l,const WordCode *r)
{
return memcmp(l, r, size);
}
int main(...)
{
WordCode a1[count], a2[count];
CmpHashArray(a1, a2);
CmpHashArray2(a1, a2);
}
is CmpHashArray have Undefined Behavior? Because with -O2 it takes 2 asm instructions instead of memcmp.
UPD:
Thanks for answer. As i see now, CmpHashArray can boil down to 1 compare if sizeof(array) <= 64bit
if this code can run faster memcmp?(on 64 and 32bit systems, crossplatform)
template<typename T,
size_t count,
typename std::enable_if<count*sizeof(T) % 64 == 0>::type
>
int CmpHashArray(const T *l,const T *r)
{
auto * l1 = reinterpret_cast<const __int64*>(l);
auto * r1 = reinterpret_cast<const __int64*>(r);
size_t iterCount = count*sizeof(T) / 64;
while(iterCount--) {
if(*l1 == *r1)
return 0;
if(*l1 < *r1)
return -1;
else
return 1;
++l1;
++r1;
}
}