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
The second code fragment avoids creation of two temporary objects (one for the
"123"converted tostd::string, the other for the return value ofsubstr), 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.