For-loop performance: storing array length in a variable

The accepted answer is not right because any decent engine should be able to hoist the property load out of the loop with so simple loop bodies.

See this jsperf – at least in V8 it is interesting to see how actually storing it in a variable changes the register allocation – in the code where variable is used the sum variable is stored on the stack whereas with the array.length-in-a-loop-code it is stored in a register. I assume something similar is happening in SpiderMonkey and Opera too.

According to the author, JSPerf is used incorrectly, 70% of the time. These broken jsperfs as given in all answers here give misleading results and people draw wrong conclusions from them.

Some red flags are putting code in the test cases instead of functions, not testing the result for correctness or using some mechanism of eliminating dead code elimination, defining function in setup or test cases instead of global.. For consistency you will want to warm-up the test functions before any benchmark too, so that compiling doesn’t happen in the timed section.

Leave a Comment