Is it possible to compare whole memory regions in a single processor cycle? More precisely is it possible to compare two strings in one processor cycle using some sort of MMX assembler instruction? Or is strcmp
-implementation already based on that optimization?
EDIT:
Or is it possible to instruct C++ compiler to remove string duplicates, so that strings can be compared simply by their memory location? Instead of memcmp(a,b)
compared by a==b
(assuming that a
and b
are both native const char*
strings).
String comparisons typically do a linear scan of the characters, returning false at the first index where characters do not match. The time complexity is O(N) and the actual time taken depends on how many characters need to be scanned before differences statistically emerge.
C strcmp()The strcmp() compares two strings character by character. If the strings are equal, the function returns 0.
You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal. Save this answer. Show activity on this post. In C because, in most contexts, an array "decays into a pointer to its first element".
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.
Just use the standard C strcmp()
or C++ std::string::operator==()
for your string comparisons.
The implementations of them are reasonably good and are probably compiled to a very highly optimized assembly that even talented assembly programmers would find challenging to match.
So don't sweat the small stuff. I'd suggest looking at optimizing other parts of your code.
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