Comparing methods for looping through an array in JavaScript

JavaScript performance comparison

Revision 16 of this test case created by molokoloco

Preparation code

an<script src="https://code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
      
<script>
Benchmark.prototype.setup = function() {
  // Fake function with minimal action on the value
  var tmp = 0;
  var process = function(value) {
      tmp = value; // Old a ref to the variable (prevent engine optim?)
  };
  
  // Declare the test Array
  var arr = [];
  for (var i = 0; i < 100000; i++) arr[i] = i;

};
</script>

Preparation code output

an

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
for()
for (var i = 0; i < arr.length; i++) process(arr[i])
pending…
for() caching
for (var i = 0, length = arr.length; i < length; i++) process(arr[i])
pending…
for() decrement
// Reversed
for (var i = arr.length - 1; i >= 0; i--) process(arr[i])
pending…
for (..in)
for (var key in arr) process(arr[key])
pending…
while() acting like for()
var i = 0;
while (i++ < arr.length) process(arr[i - 1])
pending…
while() reverse
// Reversed
var length = arr.length;
while (length--) process(arr[length])
pending…
while(..pop())
// Destructive + Reversed
var arr2 = arr.slice(0); // Copy
while(arr2.length) process(arr2.pop())
pending…
while(..shift())
// Destructive
var arr2 = arr.slice(0); // Copy
while(arr2.length) process(arr2.shift())
pending…
do while()
// Destructive
var arr2 = arr.slice(0); // Copy
do { process(arr2.shift())} while(arr2.length)
pending…
forEach()
arr.forEach(function(value) { process(value) })
pending…
map()
arr.map(function(value) { return process(value) })
pending…
$.each()
$.each(arr, function(value) { process(value) })
pending…
_.each()
_.each(arr, function(value) { process(value) })
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.

0 Comments

an