J_Ailu
J_Ailu

Reputation: 81

Fast string comparison of strings with exact length in C

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

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

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

zen
zen

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

Related Questions