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

Revision 193 of this benchmark created by ololo on


Description

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

Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout/2.2.1/knockout-min.js">
</script>
<script src="//documentcloud.github.com/underscore/underscore-min.js">
</script>
<script>
  var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
  var res = 0;
</script>

Test runner

Ready to run.

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

for (var i = 0; i < len; i++) {
  res += myArray[i];
}
window.res = res;
ready
while loop
var len = myArray.length;
while (!--len) {
  res += myArray[len];
}
window.res = res;
ready
for check index
for (var i = 0; myArray[i++];) {
  res += myArray[i];
}
window.res = res;
ready
upcount while
var len = myArray.length;
var ilen = len;
while (!--len) {
  res += myArray[ilen - len];
}
window.res = res;
ready
fastForEach
function fastForEach(array, action) {
  var len = array.length;
  var ilen = len;
  while (!--len) {
    action(array[ilen - len]);
  }
}

fastForEach(myArray, function(item) {
  res += item;
});
window.res = res;
ready
ko.utils.arrayForEach
ko.utils.arrayForEach(myArray, function(item) {
  res += item;
});
window.res = res;
ready
jquery.each
$.each(myArray, function(item) {
  res += item;
});
window.res = res;
ready
underscore
_.each(myArray, function(item) {
  res += item;
});
window.res = res;
ready

Revisions

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