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);
}
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.
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.
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 .
There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With