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

Revision 17 of this benchmark created by Andrew Russell 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; // 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 + 0.5;
    
    var arrBuf = new Float32Array(100000);
    for (var i = 0; i < 100000; i++) arrBuf[i] = i + 0.5;

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() arrBuf
for (var i = 0; i < arrBuf.length; i++) process(arrBuf[i])
ready
for() caching arrBuf
for (var i = 0, length = arrBuf.length; i < length; i++) process(arrBuf[i])
ready
_.each()
_.each(arr, function(value) { process(value) })
ready
_.each() arrBuf
_.each(arrBuf, function(value) { process(value) })
ready

Revisions

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