在stack overflow上看到了这样一个问题:为什么string
的operator==
会这么慢? 当然提问者的benchmark程序本身有问题,在编译器优化下已经完全无法测试标题中三个函数的性能了,所以这里不去讨论这个作者得到的结果。
那么,这三个函数到底哪个会快一些呢?
其实,这三个函数最终都是要进行内存的比较的,所以实际上,效率应该是相似的。但是,如果你仅仅是想判断两个 std::string
是不是相等的话,operator==
可以做的更快。
原因很简单。std::string
是会记录字符串长度的。如果仅比较相等关系,就像operator==
做的那样,那么实际可以先比较两个std::string
是不是一样长。不一样长的std::string
一定不会相等,于是operator==
其实在很多情况下根本不需要去比较内存!
string::compare()
和strcmp()
就不能这样,他们要给出两个串哪一个更大的结果,所以必须进行内存比较。更何况strcmp()
根本拿不到字符串长度信息。
最后,让我们来看一下stdlibc++的operator==
吧:
// operator ==
/**
* @brief Test equivalence of two strings.
* @param __lhs First string.
* @param __rhs Second string.
* @return True if @a __lhs.compare(@a __rhs) == 0. False otherwise.
*/
template<typename _CharT, typename _Traits, typename _Alloc>
inline bool
operator==(const basic_string<_CharT, _Traits, _Alloc>& __lhs,
const basic_string<_CharT, _Traits, _Alloc>& __rhs)
{ return __lhs.compare(__rhs) == 0; }
template<typename _CharT>
inline
typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, bool>::__type
operator==(const basic_string<_CharT>& __lhs,
const basic_string<_CharT>& __rhs)
{ return (__lhs.size() == __rhs.size()
&& !std::char_traits<_CharT>::compare(__lhs.data(), __rhs.data(),
__lhs.size())); }
这里提供两个版本。对一般的basic_string
,使用的标准规定的默认实现,compare()==0
,但同时对std::string
与std::wstring
做了优化,即首先比较了长度,并且使用了char_traits::compare()
替换了basic_string::compare()
,减少了一个函数调用,避免了basic_string::compare()
里对长度的处理。
BTW: string::compare()
与strcmp()
不是等价的。string
会记录长度,其中是可以包含字符'\0'
的。string::compare()
会按照string
的长度比较,不会遇到'\0'
停止。但是,strcmp()
会以'\0'
为字符串的终止。