Home > OS >  What's the fastest way to test if 2 strings match?
What's the fastest way to test if 2 strings match?

Time:09-29

I'm aware that the standard strcmp() function is the fastest way to test if a string is "lexicographically less than, equal to, or greater than" the other. Is strcmp() also the fastest way to see if 2 strings exactly match? If not, then what is?

CodePudding user response:

I'm aware that the standard strcmp() function is the fastest way to test if a string is "lexicographically less than, equal to, or greater than" the other. Is strcmp() also the fastest way to see if 2 strings exactly match? If not, then what is?

It sounds like the premise of the question is that there might be something faster than strcmp() because strcmp() figures out if the strings are less than or greater than, and you're thinking that maybe there's some other function that only determines if the strings match or not, and that that function would be faster because it somehow is doing less work.

No, there is no such function.

CodePudding user response:

What's the fastest way to test if 2 strings match?

strcmp() provides a speedy function that is certainly faster that any user code for a isolated general purpose string compare. strcmp() spends the lion share of its time testing for the equality of strings and only needs to compare for order as a final step - once inequity is detected. Thus even an optimized library function that only tests for equality is not expected to be significantly faster. @Barmar

Given 2 pointers to strings a, b, the fastest match test is a == b which only compares pointers. If a == b, the pointed to strings match. Yet if a != b, then the pointed to strings may still match or not.

Yet what is the higher goal for this need for the fastest way?

If we have a collection of strings to test repeatedly against a various a, we could store the collection of b stings in a hash table and very quickly compare them via their hashes.

I have used equal = a[0] == b[0] && strcmp(a,b) == 0 as a pre-test that in a given application, significantly sped up compares, yet that was time efficient given the select condition of the anticipated strings to compare and is not a general faster solution.

There are numerous way to speed up a set of string compares. We simply need to take advantage of the larger picture.

  • Related