Is performance of “less/greater than than” better than “less/greater than or equal to”

旧街凉风 提交于 2019-12-24 04:25:09

问题


Is it computationally more performant to compare less/greater than over less/greater than or equal to?

Intuitively one could think that less/greater than is marginally better.

Can a compiler use some trick to make the comparisons seem the same?

A compiler could eliminate e.g. less than or equal to with less than by incrementing the bound by one but if the bound is "alive" then this cannot be done.


回答1:


On virtually every modern CPU, there are compare/jumpless and compare/jumplessequal instructions that take exactly the same amount of time, because it runs through exactly the same hardware modulo including or not the "equals" bit.

It is the case that computing the "not less than" (and therefoe "less than") is sort of free; for unsigned values, it is equivalent to carry from a twos's complement subtraction, which the CPUs already do. Computing equal is harder: the CPU has to determine that all bits of the result of the subtraction are zero; for 64 bits CPUs, that's naively a 64 bit and-gate which is pretty big and thus slow. The CPU designers know this, and build very fast networks to detect this quickly, precisely so it isn't a bottleneck.

So the answer is "NO", or to be clear, they take the same amount of time, and there are no compiler tricks to change that.



来源:https://stackoverflow.com/questions/27016781/is-performance-of-less-greater-than-than-better-than-less-greater-than-or-equ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!