Strange optimization results

Jonathan Wakely jwakely.gcc@gmail.com
Mon Apr 11 10:16:00 GMT 2011


2011/4/11 Jonathan Wakely:
> The difference in performance may be caused by this overload of
> operator== for std::string
>
>  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())); }
>
> If that's not declared then the default operator== simply calls
> string::compare and should have similar performance at all
> optimization levels.

So to answer the original question, I'd say it's a feature, not a bug.
 operator== and string::compare are different so that operator== for
strings of different lengths will return false immediately.  Your
benchmark compares identical strings, so maybe checkingthe length
first isn't an optimization, but for many examples in real code it is
faster to avoid comparing every character in the string if the lengths
aren't the same.



More information about the Gcc-help mailing list