Reputation: 5575
Say we have a string var "sA" and I would like to check whether the string "123" is at the end of the sA.
What is better to do and why:
if(sA.length() > 2) sA.substr(sA.length()-3) == "123"
if(sA.length() > 2) sA.find("123", sA.length() -3) != string::npos
Thanks in advance
Upvotes: 2
Views: 2485
Reputation: 30301
If performance is critical, I don't think you can get any faster than this (compared to the other methods, no allocations are necessary):
const char needle[] = "abc";
const char *haystack;
const int len = strlen(haystack);
if (len<sizeof(needle))
return false;
for (int i=0; i<sizeof(needle); i++)
if (needle[i] != haystack[len-sizeof(needle)+i])
return false;
return true;
Obviously various micro-optimizations are possible, but the approach is the fastest I can think of.
A more C++y version, using std::string for the haystack:
const char needle[] = "abc";
const std::string haystack;
const int len = haystack.length();
if (len<sizeof(needle))
return false;
for (int i=0; i<sizeof(needle); i++)
if (needle[i] != haystack[len-sizeof(needle)+i])
return false;
return true;
notice that, as long as std::string::operator[]
is O(1), the two listings have the same performance characteristics
Upvotes: 2
Reputation: 2305
This code probably is faster than the ones you are testing. But you will only know if you do some testing.
bool EndsWith(const string &strValue, const string &strEnd)
{
int iDiference = strValue.size() - strEnd.size();
if(iDiference >= 0)
return (memcmp(strValue.c_str() + iDiference, strEnd.c_str(), strEnd.size()) == 0);
return false;
}
Upvotes: 1
Reputation: 726589
The second code fragment avoids creation of two temporary objects (one for the "123"
converted to std::string
, the other for the return value of substr
), so in theory it should be faster. However, micro-optimizations of this sort rarely pay off: it is unlikely that you would see a substantial gain from using the second form over the first one if you apply this optimization randomly.
Of course the situation is different if your profiler tells you that your program spends a substantial percentage of its time checking the ending of the string like this; in this case, the optimization will likely help.
Upvotes: 4