Reputation: 33
Would anyone please be able to tell me the most efficient way to compare two constant char stars?
#include <iostream>
#include <string>
int main()
{
const char* value1 = "hello";
const char* value2 = "HELLO";
const char* possibility = NULL;
if(stricmp(value1, value2)==0)
{
std::cout <<"\nThey Match!!!!!" << std::endl;
}
else{std::cout << "\nThey dont match :("<< std::endl;}
return 0;
}
I used the following standard function but I know its not the most efficient way to do this?
Besides stricmp
cannot handle NULL which in my case has a possibility of occurring.
So is there any other alternatives good for performance?
Thanks in advance
Upvotes: 3
Views: 8582
Reputation: 41444
There is no efficient way to compare two character strings.
There are a couple of ways to improve on the basic stricmp()
, if it shows up very high on a profile (which I have seen in real apps). You may find that the bulk of the cost is in tolower()
, which is a function called on each character to convert it from upper to lowercase before comparison. The overhead of this function call, plus the cost of its body, can add up to significant time, because it must be locale-sensitive and deal with letters like Ö. If you know that your comparisons will only ever be performed in one locale (ie, only in English), then you can speed up tolower() by building a 256-character ASCII lookup table and implementing stricmp() manually.
With GCC, if you know you are targeting a CPU that supports SSE3, you can also specify the -msse3
command line switch that generates slightly more efficient machine instructions for the string comparison. It mostly helps case sensitive comparison, however.
In my line of work, any algorithm that requires comparing lots of constant character strings, as opposed to using interns or symbols to represent such identifiers, is considered a code smell. On one project, profiling indicated that about 7% of the CPU time was spent inside tolower() inside stricmp
. That is effectively 7 out of 100 machines per data center doing nothing but turning uppercase letters into lowercase ones.
Upvotes: 7
Reputation: 13097
stricmp
is probably faster than anything you can write yourself, and you shouldn't bother unless you know that this will be the bottleneck in your program's performance.
Upvotes: 2