Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ string comparison in one clock cycle

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).

like image 577
AareP Avatar asked Jul 14 '09 21:07

AareP


People also ask

How much time does string comparison take?

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.

Can you compare C strings?

C strcmp()The strcmp() compares two strings character by character. If the strings are equal, the function returns 0.

Can you compare C strings with ==?

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".

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.


1 Answers

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.

like image 92
greyfade Avatar answered Oct 09 '22 21:10

greyfade