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
:
str1 != str2
, the compiler now translates this to (str1 <=> str2) != 0
.!=
for string
would have first checked for str1.size() != str2.size()
, and only on failure moved to comparing the actual characters.So if this is truely how strings are compared for inequality now, isn't this a huge performance loss?
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 <=>
.