Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 719
J_Ailu Avatar asked Jan 28 '13 14:01

J_Ailu


People also ask

How do you compare two strings of different lengths?

if you use std::string, for comparison you can either use the compare function or use relational operators, provided with this class. if (str1 != str2) std::cout << "str1 and str2 are not equal\n"; all other relational operators, i.e., == < > <= >= are also available.

Can I use == to compare strings in C?

In C, string values (including string literals) are represented as arrays of char followed by a 0 terminator, and you cannot use the == operator to compare array contents; the language simply doesn't define the operation.

Is strcmp faster than ==?

While comparing the two function, in a loop repeted 500'000'000 times, strcmp execute too much fast, about x750 times faster. The execution time of that function is 3.058s , while strcmp only 0.004s .

What are the 3 ways to compare two string objects?

There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.


Video Answer


1 Answers

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.

like image 64
Sergey Kalinichenko Avatar answered Oct 07 '22 13:10

Sergey Kalinichenko