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

时光总嘲笑我的痴心妄想 提交于 2019-12-17 21:01:14

问题


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 find myself mixing the use of these operators within my code. Any thoughts would be appreciated.


回答1:


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.




回答2:


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.




回答3:


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?




回答4:


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!



来源:https://stackoverflow.com/questions/5861222/comparison-operator-performance

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