Comparing methods for looping through an array in JavaScript (v19)

Revision 19 of this benchmark created on


Description

Comparing methods for looping through an array of 100000 items and do a minimal operation with the new value each time.

Test rendered values here :

Disclamer

In this new test, array is not regenerated for each benchmarks because of destructive methods (cf. https://twitter.com/molokoloco/status/443013019548020736) You can compare .pop() / .shift() between themselves, acknowledging they also copy the array for each test...

Working on this i have just found a lot of bugs (at the end ^^)...

This big broken test, for the use of only one array and some destructive methods... (all the tests after shift() or pop() run with an empty array)

Ressources

Thanks you peoples of JS ;)

Preparation HTML

an<script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>

Setup

// Fake function with minimal action on the value
    var tmp = 0;
    var process = function(value) {
        tmp = value; // Hold a ref to the variable (prevent engine optim?)
    };
    
    // Declare the test Array
    var arr = [];
    var arrBuf = new Float32Array() || [];
    
    for (var i = 0; i < 100000; i++) {
        arr[i] = i;
        arrBuf[i] = i + 0.1;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
for()
for (var i = 0; i < arr.length; i++) process(arr[i])
ready
for() caching
for (var i = 0, length = arr.length; i < length; i++) process(arr[i])
ready
for() decrement
// Reversed
for (var i = arr.length - 1; i >= 0; i--) process(arr[i])
ready
for (..in)
for (var key in arr) process(arr[key])
ready
while() acting like for()
var i = 0;
while (i++ < arr.length) process(arr[i - 1])
ready
while() reverse
// Reversed
var length = arr.length;
while (length--) process(arr[length])
ready
while(..pop())
// Destructive + Reversed
var arr2 = arr.slice(0); // Copy
while(arr2.length) process(arr2.pop())
ready
while(..shift())
// Destructive
var arr2 = arr.slice(0); // Copy
while(arr2.length) process(arr2.shift())
ready
do while()
// Destructive
var arr2 = arr.slice(0); // Copy
do { process(arr2.shift())} while(arr2.length)
ready
forEach()
arr.forEach(process)
ready
map()
arr.map(process)
ready
$.each()
$.each(arr, process)
ready
_.each()
_.each(arr, process)
ready
for with Float32Array
for (var i = 0; i < arrBuf.length; i++) process(arrBuf[i])
ready

Revisions

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