JavaScript loop performance – Why is to decrement the iterator toward 0 faster than incrementing

I’m not sure about Javascript, and under modern compilers it probably doesn’t matter, but in the “olden days” this code:

for (i = 0; i < n; i++){
  .. body..
}

would generate

move register, 0
L1:
compare register, n
jump-if-greater-or-equal L2
-- body ..
increment register
jump L1
L2:

while the backward-counting code

for (i = n; --i>=0;){
  .. body ..
}

would generate

move register, n
L1:
decrement-and-jump-if-negative register, L2
.. body ..
jump L1
L2:

so inside the loop it’s only doing two extra instructions instead of four.

Leave a Comment