Browser Diet - jQuery.each vs. for loop (v48)

Revision 48 of this benchmark created on


Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js">
</script>
<script>
  var a = $('*').get(),
      e, breaker = {};



var myEach = function(obj, iterator, context) {
  if (obj == null) return obj;
  if (obj.length === +obj.length) {
    for (var i = 0, length = obj.length; i < length; i++) {
      iterator.call(context, obj[i], i, obj);
    }
  } else {
    var keys = _.keys(obj);
    for (var i = 0, length = keys.length; i < length; i++) {
      iterator.call(context, obj[keys[i]], keys[i], obj);
    }
  }
  return obj;
};


var myEachSmartContext = function(obj, iterator, context) {
  if (context) {
    return myEach(obj, iterator, context);
  }

  if (obj == null) return obj;
  if (obj.length === +obj.length) {
    for (var i = 0, length = obj.length; i < length; i++) {
      iterator(obj[i], i, obj);
    }
  } else {
    var keys = _.keys(obj);
    for (var i = 0, length = keys.length; i < length; i++) {
     iterator(obj[keys[i]], keys[i], obj);
    }
  }
  return obj;
};
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
jQuery.each
$.each(a, function() { e = this; })
ready
for loop
for (var i = 0, len = a.length; i < len; i++) { e = a[i]; }
ready
native forEach
a.forEach(function(elem) { e = elem; })
ready
native forEach (right args)
a.forEach(function(elem, e_i, e_a) { e = elem; })
ready
no context underscore
myEachSmartContext(a, function(elem, e_i, e_a) { e = elem; })
ready
non-native underscore
myEach(a, function(elem, e_i, e_a) { e = elem; })
ready
underscore.each
_.each(a, function (elem, e_i, e_a) { e = elem });
ready

Revisions

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