Home > Enterprise >  Ordered vs equality comparison of integers
Ordered vs equality comparison of integers

Time:10-16

There are many situations where integers could be compared with either ordered or equality comparison; if you know i will never be greater than j, then i < j and i != j are equivalent. And typically run at the same speed.

It is theoretically possible for ordered comparison that has to propagate the carry flag across all 64 bits, to be a cycle slower than equality comparison, but as far as I know, this is not typically the case.

Are there any existing or in-development CPUs where there is even a single cycle difference in speed between the two comparison operators (on machine-word numbers, not bignums)?

CodePudding user response:

Yes. However, this is complex and very dependent (of possibly some tricky behaviours) of the specific target processor.

On all modern desktop/server x86-64 processors (e.g. Intel and AMD processors), the cost is the same for the scalar assembly instructions resulting from the >, <, '==' and != operators. The cmp and test instructions are used for that (and are equally fast). It was not true in the past where the test instruction was a bit faster and so the == and != operators. However, this is not true for SSE/AVX SIMD instructions on 64-bits registers on Intel processors: the equality operators are faster than the ordered comparison operators (higher reciprocal throughput and lower latency). For SSE/AVX SIMD instructions on 64-bits registers on AMD processors, this a bit more complex: Zen/Zen2 behaved the same way than Intel processors but the latency is the same for both operation, and on Zen3 using ordered comparison operators is actually at least as fast as equality operators (experiments show it is surprisingly even faster due to a higher dedicated ports). The situation is different with SSE/AVX on 32-bit registers or with AVX-512 (both comparison operators behave the same).

As far as I know, on most ARM processors, the TST instruction is as fast the CMP one, and on POWER processors, there is only one instruction used for the two kind of operators and so the operators should be equally fast. I expect the equality operators to be often as fast as the ordered comparison operators and in some cases faster. However, I am pretty sure, there is some weird processor (possibly non-standard ARM processors) were this is not the case. Still, this is very uncommon on mainstream processors.

  • Related