Fastest array loops in Javascript (v133)

Revision 133 of this benchmark created on


Preparation HTML

<script src="https://code.jquery.com/jquery-git2.min.js"></script>

Setup

// Populate the base array
  var arr = [];
  for (var i = 0; i < 20; i++) {
    arr[i] = (Math.random() * 1000 |0);
  }
  
  function someFn(ix) {
    return ix << 1;
  }
  var len = arr.length, i = 0, arr2 = arr.slice();

Teardown



            i = 0; // reset counters if modified
  arr = arr2.slice(); // repopulate by copying back
        
  

Test runner

Ready to run.

Testing in
TestOps/sec
For loop, basic
for (var i = 0; i < arr.length; i++) {
  someFn(arr[i]);
}
ready
While loop, basic
while (i < len) {
  someFn(arr[i]);
  i++;
}
ready
For loop, cached+init
for (var i = 0; i < len; i++) {
  someFn(arr[i]);
}
ready
For loop, i--
for (var i = len; i > 0; i--) {
  someFn(arr[i]);
}
ready
Do-while loop, i--
var i = len - 1;
do {
  someFn(arr[i]);
} while (i--);
ready
Do-while loop, --i
var i = len;
if (i > 0) {
  do {
    someFn(arr[i]);
  }
  while (--i);
}
ready
For..in loop
for (var i in arr) {
  someFn(arr[i]);
}
ready
shift 1
while (i = arr.shift()) {
  someFn(arr[i]);
}
ready
forEach
arr.forEach(function(v) {
  someFn(arr[v]);
})
ready
shift 2
while ((i = arr.shift()) !== undefined) {
  someFn(arr[i]);
}
ready
While ! Undefined
var a;
while ((a = arr[i++]) !== undefined) {
  someFn(arr[a]);
}
ready
Pop
while ((i = arr.pop()) !== undefined) {
  someFn(arr[i]);
}
ready
Order w/ array copy
var copy = arr.slice(0);
while (i = copy.shift()) {
  someFn(arr[i]);
}
ready
While length--
var l = len;
while (l--) {
  someFn(arr[l]);
}
ready
pop2
i = arr.pop();
while (i !== undefined) {
  someFn(arr[i]);
  i = arr.pop();
}
ready
non-init for
for (; i < len; ++i) {
  someFn(arr[i]);
}
ready
Object.keys
Object.keys(arr).forEach(function(i) {
	someFn(arr[i]);
});
ready
while non cached len
while (i < arr.length) {
  someFn(arr[i]);
  i++;
}
ready
while obj.keys.length
var i = Object.keys(arr).length;
while (i--) {
  someFn(arr[i]);
}
ready
jQuery
$.each(arr, function(index, value) {
 someFn(arr[value]);
});
ready
pop3
while (i = arr.pop()) {
  someFn(arr[i]);
}
ready
shift 3
i = arr.shift();
while (i !== undefined) {
  someFn(arr[i]);
  i = arr.shift();
}
ready
while loop - uncached i and length
var j = 0;
while (j<arr.length) {
  someFn(arr[j]);
  j++;
}
ready
while -= 1
var l = len;
while (l -= 1) {
  someFn(arr[l]);
}
ready

Revisions

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