$.each vs for in (v4)

Revision 4 of this benchmark created on


Description

Purpose of this test case is to test the performance difference between using jQuery.each or using the original javascript 'for in' construct. JavaScript's 'for in' also loops through prototype properties of the object being iterated through whereas $.each doesn't.

Update: it looks like jquery 1.6.2 has brought in $.each optimisations. Either that, or recently released browsers have much faster processing for $.each.

Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
  Array.prototype.filter_0 = function() {
   var res = [];
   for (var i = 0, len = this.length; i < len; i++) {
    if (this[i] !== 0) {
     res.push(this[i]);
    }
   }
   return res;
  };
  var listeners = ["a", "b", "c"];
  var x = 0;
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
for in
var o = '', x = 0;
for (o in listeners) {
 x++;
}
ready
$.each
var x = 0;
$.each(listeners, function(key) {
 x++;
});
ready
for in only named elems
var o = '', x = 0;
for (o in listeners) {
 if (listeners.hasOwnProperty(o)) {
  x++;
 }
}
ready
for each ... in
var o = '', x = 0;
for each (o in listeners) {
 if (listeners) {
  x++;
 }
}
ready

Revisions

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