Search code examples
c++performancecomparisonc++20spaceship-operator

Will the C++20 spaceship operator be used for equality/inequality comparisons?


Since C++20 the standard library uses the spaceship operator to implement comparison for strings and vectors (according to this video). I am worried that this comes with a potentially huge performance penalty!

Let me explain on the example of the operator != for string:

  • When I write str1 != str2, the compiler now translates this to (str1 <=> str2) != 0.
  • However, an efficient implementation of != for string would have first checked for str1.size() != str2.size(), and only on failure moved to comparing the actual characters.
  • This optimization cannot be implemented for the spaceship operator, as it has to determine the "larger" string anyway.

So if this is truely how strings are compared for inequality now, isn't this a huge performance loss?


Solution

  • That was already addressed by the standardization committee in http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1185r2.html. That change says that a == b and a != b are not calling operator <=>, they are calling operator== and operator !=. The behavior that you describe was a temporary version of the C++20 standard that was later revised.

    The linked change request exactly gives std::vector as an example where == can compare more efficiently than <=>.