Array length in a variable versus per-iteration access of array length in a for loop

JavaScript performance comparison

Test case created by Nathaniel


Storing the length property of an array that will be iterated through with a for loop into a variable is an old school performance optimization for JavaScript. Browsers have since evolved to better handle these sorts of minor optimizations. Interested in seeing whether this optimization is still beneficial in today's browsers.

Preparation code

Benchmark.prototype.setup = function() {
    var i, l, x, arr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Store the array length in a variable
for (i = 0, l = arr.length; i < l; i++) { x = arr[i]; }
Access the array length property each time
for (i = 0; i < arr.length; i++) { x = arr[i]; }

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers


Comment form temporarily disabled.

Add a comment