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

Revision 73 of this benchmark created on


Description

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

Setup

var myArray = [];
      for (var i = 1000; i--;) myArray.push(i);

Test runner

Ready to run.

Testing in
TestOps/sec
With caching
for (var i = 0, len = myArray.length; i < len; i++) {
  myArray[i];
}
ready
Without caching
for (var i = 0; i < myArray.length; i++) {
  myArray[i];
}
ready
Counting down
for (var i = myArray.length; i--;) {
  myArray[i];
}
ready
caching length outside for loop
var len = myArray.length;

for (var i = 0; i < len; i++) {
  myArray[i];
}
ready
while loop
var len = myArray.length;
while (len--) {
  // blah blah
  myArray[len];
}
ready
for check index
for (var i = 0; myArray[i++];) {
  myArray[i];
}
ready
caching, !==
for (var i = 0, len = myArray.length; i !== len; i++) {
  myArray[i];
}
ready
destructive while
var a;
while ((a = myArray.shift()) !== undefined) {
  a;
}
ready
nondestructive while
var a, i = 0;
while ((a = myArray[i++]) !== undefined) {
  a;
}
ready

Revisions

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