Internally, string::operator==() is using string::compare(). Please refer to: CPlusPlus - string::operator==()
I wrote a small application to compare the performance, and apparently if you compile and run your code on debug environment the string::compare() is slightly faster than string::operator==(). However if you compile and run your code in Release environment, both are pretty much the same.
FYI, I ran 1,000,000 iteration in order to come up with such conclusion.
In order to prove why in debug environment the string::compare is faster, I went to the assembly and here is the code:
DEBUG BUILD
string::operator==()
if (str1 == str2) 00D42A34 lea eax,[str2] 00D42A37 push eax 00D42A38 lea ecx,[str1] 00D42A3B push ecx 00D42A3C call std::operator==<char,std::char_traits<char>,std::allocator<char> > (0D23EECh) 00D42A41 add esp,8 00D42A44 movzx edx,al 00D42A47 test edx,edx 00D42A49 je Algorithm::PerformanceTest::stringComparison_usingEqualOperator1+0C4h (0D42A54h)
string::compare()
if (str1.compare(str2) == 0) 00D424D4 lea eax,[str2] 00D424D7 push eax 00D424D8 lea ecx,[str1] 00D424DB call std::basic_string<char,std::char_traits<char>,std::allocator<char> >::compare (0D23582h) 00D424E0 test eax,eax 00D424E2 jne Algorithm::PerformanceTest::stringComparison_usingCompare1+0BDh (0D424EDh)
You can see that in string::operator==(), it has to perform extra operations (add esp, 8 and movzx edx,al)
RELEASE BUILD
string::operator==()
if (str1 == str2) 008533F0 cmp dword ptr [ebp-14h],10h 008533F4 lea eax,[str2] 008533F7 push dword ptr [ebp-18h] 008533FA cmovae eax,dword ptr [str2] 008533FE push eax 008533FF push dword ptr [ebp-30h] 00853402 push ecx 00853403 lea ecx,[str1] 00853406 call std::basic_string<char,std::char_traits<char>,std::allocator<char> >::compare (0853B80h)
string::compare()
if (str1.compare(str2) == 0) 00853830 cmp dword ptr [ebp-14h],10h 00853834 lea eax,[str2] 00853837 push dword ptr [ebp-18h] 0085383A cmovae eax,dword ptr [str2] 0085383E push eax 0085383F push dword ptr [ebp-30h] 00853842 push ecx 00853843 lea ecx,[str1] 00853846 call std::basic_string<char,std::char_traits<char>,std::allocator<char> >::compare (0853B80h)
Both assembly code are identical as the compiler perform optimization.
Finally, in my opinion, the performance gain is negligible, hence I would really leave it to the developer to decide on which one is the preferred one as both achieve the same outcome (especially when it is release build).
if(x.compare(y) == 0)<- equals sign, it's equal. IMO using!only serves to make code unreadable.comparereturn-1ifsis lower thantand+1ifsis greater thantwhile==returntrue/false. Nonzero integers aretrueand0isfalse.