Array iteration methods microbenchmark

JavaScript performance comparison

Test case created by Shah-Nisarg

Preparation code

  <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
      
<script>
Benchmark.prototype.setup = function() {
         
    // A function to generate GUID's that can be used to populate the array.
    // https://stackoverflow.com/a/2117523/5894241
    function uuidv4() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
      });
    }
    
    // Populate the array.
    var arr = new Array();
    var arraySize = 1000;
    for(var i = 0; i < arraySize; i++) {
      arr.push(uuidv4());
    }
  
  
    function doSomething(item) {
      // Do the total to prevent the compiler from optimizing this line away.
      sum += item.length;
    }
  
  var sum;

};
</script>

Preparation code output

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
Array#forEach
sum = 0;
arr.forEach(function(item) {
  x = doSomething(item);
});
console.log(sum);
pending…
Lodash
sum = 0;
_.each(arr, function(item) {
  x = doSomething(item);
});
console.log(sum);
pending…
for
var length = arr.length;
sum = 0;
for(var i = 0; i < length; i++) {
  x = doSomething(arr[i]);
}
console.log(sum);
pending…
while
var i = arr.length;
sum = 0;
while (--i >= 0) {
    doSomething(arr[i]);
}
console.log(sum);
pending…

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

Compare results of other browsers

0 Comments