Is it worth caching the length of an array in a Javascript loop?

JavaScript performance comparison

Revision 43 of this test case created

Info

http://stackoverflow.com/questions/5349425/whats-the-best-to-loop-an-array-in-javascript

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div id="test1"></div>
<div id="test2"></div>
<div id="test3"></div>
<div id="test4"></div>
<div id="test5"></div>
<div id="test6"></div>
<div id="test7"></div>
<div id="test8"></div>
<div id="test9"></div>
<script>
  var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
With caching
var test = $("#test1")
for (var i = 0, len = myArray.length; i < len; i++) {
test.append(i)
}
pending…
Without caching
var test = $("#test2")
for (var i = 0; i < myArray.length; i++) {
test.append(i)
}
pending…
Counting down
var test = $("#test3")

for (var i = myArray.length; i--;) {
test.append(i)
}
pending…
caching length outside for loop
len = myArray.length;
var test = $("#test4")

for (var i = 0; i < len; i++) {
test.append(i)
}
pending…
while loop
var test = $("#test5")
len = myArray.length;
while (len--) {
test.append(len)
}
pending…
for check index
var test = $("#test6")
for (var i = 0; myArray[i++];) {
test.append(i)
}
pending…
Prefix incr
var test = $("#test7")
for (var i = 0, len = myArray.length; i < len; ++i) {
test.append(i)
}
pending…
Do
var test = $("#test8")
i = myArray.length - 1
do {
test.append(i)
} while(i--)
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment