开发者

Comparison operator performance (>, >=, <, <=)

开发者 https://www.devze.com 2023-03-01 22:50 出处:网络
If you were to compare two integers, would the operator have an impact on the time required to perform the comparison? For example, given:

If you were to compare two integers, would the operator have an impact on the time required to perform the comparison? For example, given:

if (x < 60)

and

if (x <= 59)

Which would provide the best performance, or would the performance difference be negligible? Are the performance results language-dependent?

I often fin开发者_开发问答d myself mixing the use of these operators within my code. Any thoughts would be appreciated.


Even if there was noticeable difference, I think compilers are smart enough to care for such things. So my advice is to use what makes the code easier to understand, and leave micro-optimizations to the compiler.


In the specific example you gave where one side is constant, I'd expect an optimizer to transform one to the other if it was significantly faster.


The differences are negligible. Theoretically they could be language dependent.

As another answer mentioned, they are also theoretically platform dependent.

See: Is the inequality operator faster than the equality operator?


There is almost certainly no difference in performance. For CISC processors, you'll typically have all manner of branch instructions that cope with all the difference < <= > >= etc. On RISC there may be a very small performance difference although I'd seriously doubt it!

0

精彩评论

暂无评论...
验证码 换一张
取 消