问题
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