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

Revision 198 of this benchmark created by ckknight on


Description

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

Preparation HTML

<script>
  var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
  function f(x) {
    return x;
  }
</script>

Test runner

Ready to run.

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

for (var i = 0; i < len; ++i) {
  f(myArray[i]);
}
ready
while loop
var i = myArray.length;
while (i--) {
  f(myArray[i]);
}
ready
Counting down with decrement in step
for (var i = myArray.length - 1; i >= 0; --i) {
  f(myArray[i]);
}
ready
Counting down with decrement in step, checking against !== -1
for (var i = myArray.length - 1; i !== -1; --i) {
  f(myArray[i]);
}
ready

Revisions

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