13

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.

Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
  • 7
    Yes, there indeed is a performance difference (at least in JavaScript): on my machine `x < 60` takes 1103,1 picoseconds to execute, and `x <= 59` takes 1103,2 picoseconds to execute, making it a tenth of a picosecond slower. Mind blown `:)` [See for yourself](http://jsperf.com/less-than-vs-greater-than-or-equal) – Šime Vidas May 02 '11 at 19:10
  • @Šime Vidas: That's pretty cool. Those results are definitely browser-dependent. – Evan Mulawski May 02 '11 at 19:15
  • 2
    Yes, in IE9 `<=` is in fact 32% slower (!!) (which is 2.7 nanoseconds on my machine). – Šime Vidas May 02 '11 at 19:18

4 Answers4

11

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.

Alexey Kukanov
  • 12,479
  • 2
  • 36
  • 55
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.

AShelly
  • 34,686
  • 15
  • 91
  • 152
1

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?

Community
  • 1
  • 1
Thomas Langston
  • 3,743
  • 1
  • 25
  • 41
0

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!

Will A
  • 24,780
  • 5
  • 50
  • 61