2

Which one is more efficient?

// < 11
for(var i = 0; i < 11; i++){ ... }

or

// <= 10
for(var i = 0; i <= 10; i++){ ... }

I don't know exactly how the for function works but I'm assuming that < 11 is more effiecient because in <= 10 it seems that in each 10 comparisons it has too check if it is equal too, not just smaller so it has to make 2 comparisons instead of one.

Am I right, or how this works?

Adam Halasz
  • 57,421
  • 66
  • 149
  • 213
  • 7
    [jsPerf.com](http://jsperf.com), looks like the first one [was negligibly faster](http://jsperf.com/loopcompare-15272284) on FF18, but does it really matter? – Chad Mar 07 '13 at 13:19
  • 8
    I see you found the bottle-neck of your app... congrats. BTW, `i++`?! it may be a lot faster using `i= i+1`! check it as well. – gdoron Mar 07 '13 at 13:20
  • compiler is very smart, it always perform the single compare as i < 11. the code i<= 10 is converted to i < 11. – Romil Kumar Jain Mar 07 '13 at 13:22
  • check:http://stackoverflow.com/questions/11763399/which-operator-is-faster-or-or – Amrendra Mar 07 '13 at 13:25
  • Hey thanks @Chad awesome! I think it matters with a lots of for loops :P. Could you post that as an answer? :) – Adam Halasz Mar 07 '13 at 13:26

2 Answers2

6

If there is any difference at all, it would be very small. You should use the code that is easier to maintain. Usually the < operator is preferred, because looping from 0 while the counter is < x gives x iterations.

However, any difference is not because the <= does two comparisons, because it doesn't.

When comparing two numeric values, the computer actually subtracts them, and checks what happens. If the result is positive, negative or zero, different operators give a true result:

operator:   true when result is:
----------  ---------------------
<           negative
<=          not positive
==          zero
>           positive
>=          not negative
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
6

Anytime you have a performance question, always get it out on jsPerf.com.

With this test case:

  • In FF18 the first loop is negligibly faster
  • In FF19 the second loop is negligibly faster.
  • In Chrome 25 they are exactly the same.

Really this is at best a micro-pre-optimization, and you should probably focus elsewhere.

Chad
  • 19,219
  • 4
  • 50
  • 73