Reputation: 81
Does anyone has an idea what will be the fastest way of a string comparison for strings with exactly 6 chars ?
My idea is the following:
inline bool jfStrEq6(const char *s1, const char *s2)
{
uint64_t s1ui64 = *((uint64_t *)s1);
uint64_t s2ui64 = *((uint64_t *)s2);
return (s1ui64 & 0x0000ffffffffffff) == (s2ui64 & 0x0000ffffffffffff);
}
Upvotes: 8
Views: 237
Reputation: 726569
This is undefined behavior: you read past the last valid byte of a 6-character string. Only seven, not eight, bytes are OK to read. In addition, byte order matters: you may need 0xffffffffffff0000
on some architectures.
If you know the length of your string, use memcmp
:
inline bool jfStrEq6(const char *s1, const char *s2) {
return !memcmp(s1, s2, 6);
}
Chances are, your optimizer will convert this to a CPU intrinsic for a fastest comparison possible on your platform.
Upvotes: 9
Reputation: 122
what do you think of xor?
return !(s1ui64 ^ s2ui64);
But I'm not sure if it is really faster, but at least shorter.
Upvotes: -2