Browser Diet - jQuery.each vs. for loop

JavaScript performance comparison

Revision 48 of this test case created

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="//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>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

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

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment