for, foreach, $.each (v5)

Revision 5 of this benchmark created by Firepolo on


Description

native for vs native forEach vs jquery each vs underscore each

Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="//underscorejs.org/underscore-min.js"></script>

Setup

var add = function(a, b) {
      return a + b;
    };
    
    var values = [];
    for (i = 0; i < 10000; i++) {
      values[i] = Math.random();
    }
    
    function Arr() {}
    Arr.each = function(arr, callback) {
      for (var i = 0; i < arr.length; i++) callback(i, arr[i]);
    };

Test runner

Ready to run.

Testing in
TestOps/sec
for
for (var i = 0; i < values.length; i++) {
  var value = values[i];
  add(1, value);
}
ready
forEach
values.forEach(function(element) {
  add(1, element);
});
ready
$.each
$(values).each(function(index, value) {
  add(1, value);
});
ready
_.each
_.each(values, function(item) {
  add(1, item);
});
ready
custom for(each)
for (var i = 0, value;
  (value = values[i]); i = i + 1) {
  add(1, value);
}
ready
for (optimized)
for (var i = 0; i < values.length; i++) add(1, values[i]);
ready
Arr.each
Arr.each(values, function(i, item) {
  add(1, item);
});
ready

Revisions

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

  • Revision 5: published by Firepolo on