'Performance problems with the C++20 spaceship operator?
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
!=
forstring
would have first checked forstr1.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 1:[1]
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 <=>
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | OverShifted |