在内部, string::operator==()
使用了 string::compare()
。请参考:CPlusPlus - string::operator==()
我写了一个小程序来比较性能,显然如果您在调试环境下编译和运行代码,string::compare()
比 string::operator==()
稍微快一点。但是如果您在发布环境下编译和运行代码,两者几乎相同。
顺便说一下,我运行了100万次迭代才得出这样的结论。
为了证明为什么在调试环境中 string::compare 更快,我查看了汇编代码:
调试版本
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)
你可以看到,在string::operator==()中,需要执行额外的操作(add esp, 8和movzx edx,al)。
发布版本
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)
两种汇编代码非常相似,因为编译器执行了优化。
最后,在我看来,性能提升可以忽略不计,因此我真的会把选择权交给开发者决定哪个更好,因为两个都可以达到相同的结果(特别是在发布构建时)。
if(x.compare(y) == 0)
<- 等号,表示相等。在我看来,只使用!
只会使代码难以阅读。 - R. Martinho Fernandescompare
如果s
小于t
则返回-1
,如果s
大于t
则返回+1
,而==
则返回true/false
。非零整数为true
,0为false
。 - ghchoi