[Bug libstdc++/59048] operator== between std::string and const char* slower than strcmp
msebor at gcc dot gnu.org
gcc-bugzilla@gcc.gnu.org
Fri May 19 04:06:00 GMT 2017
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59048
Martin Sebor <msebor at gcc dot gnu.org> changed:
What |Removed |Added
----------------------------------------------------------------------------
Keywords| |missed-optimization
Status|UNCONFIRMED |NEW
Last reconfirmed|2013-11-08 00:00:00 |2017-05-19
CC| |msebor at gcc dot gnu.org
Ever confirmed|0 |1
--- Comment #16 from Martin Sebor <msebor at gcc dot gnu.org> ---
Confirmed.
I don't think the char* overload can ever match the string overload because the
former has to compute the length of the char* argument and (possibly also)
compare the strings, while the latter can avoid the first step because the
lengths of both arguments are precomputed.
But the char* overload can be sped up by avoiding string::compare which always
traverses the strings, when operator== only has to do that if their lengths are
the same.
It also doesn't help that string::compare is not expanded inline (because
std::string is declared extern).
In my tests, the following definition speeds the operator up by a factor of 5,
making it about 20% faster than strcmp:
template<typename _CharT>
inline bool
operator==(const basic_string<_CharT>& __lhs,
const _CharT* __rhs)
{
return !__lhs.compare (__rhs);
typedef typename basic_string<_CharT>::size_type size_type;
const size_type __len1 = __lhs.length ();
const size_type __len2 = __builtin_strlen (__rhs);
return __len1 == __len2
&& !char_traits<_CharT>::compare (__lhs.data (), __rhs,
__len1 < __len2 ? __len1 : __len2);
}
More information about the Gcc-bugs
mailing list