Underscore.each vs jQuery.each vs. for loop (v235)

Revision 235 of this benchmark created by Dan DeFelippi on


Description

Modified to access array elements in all loops. Previous for loops were an unfair comparison because they never actually accessed the array. Also removed calls to functions in loops. Those are an entirely different test that don't belong here.

Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script src="//documentcloud.github.com/underscore/underscore-min.js">
</script>
<script>
  var a = new Array(100000),
      e;

  var ArrayIterator = function(array) {
      this.array = array;
      this.index = -1;
      };

  ArrayIterator.prototype.next = function() {
    return this.index < (this.array.length - 1);
  };

  ArrayIterator.prototype.current = function() {
    this.index += 1;
    return this.array[this.index];
  };

  function each(array, func) {
    for (var i = 0, l = array.length; i < l; i++) {
      if (func.call(this, i, array[i]) === false) return;
    }

    return true;
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
jQuery.each
$.each(a, function(i, value) {
  e = value;
});
ready
good old for loop
for (var i = 0, len = a.length; i < len; i++) {
  e = a[i];
};
ready
underscore.each
_.each(a, function(value) {
  e = value;
});
ready
good old for loop (decrementing)
for (var i = a.length; i > 0; i--) {
  e = a[i];
};
ready
Iterator pattern
var it = new ArrayIterator(a);
while (it.next()) {
  e = it.current();
}
ready
Simpler each
each(a, function(index, value) {
  e = value;
});
ready

Revisions

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