array iteration

JavaScript performance comparison

Revision 4 of this test case created by keville and last updated

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  // create a set of items over which to iterate
  var items = [];
  (function () {
    for (var i = 0; i < 10000; i++) {
       items[i] = i;
    }
  })();
  // create an object to host the method so we can
  // demonstrate scope correction
  var widget = {
    addNumberToItself: function (num) {
      return num + num;
    }  
  };
  
  // define some custom array iterators to test inlining
  
  Array.prototype.customForEachWithBind = function (fn, scope) {
    fn = fn.bind(scope || null);
    for (var i = 0, count = this.length; i < count; i++) {
      fn(this[i], i, this);
    }
  };
  
  Array.prototype.customForEachWithApply = function (fn, scope) {
    scope = scope || null;
    for (var i = 0, count = this.length; i < count; i++) {
      fn.apply(scope, [this[i], i, this]);
    }
  };

};
</script>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
traditional for
for (var i = 0, len = items.length; i < len; i++) {
  widget.addNumberToItself(items[i]);
}
pending…
Array.forEach() 1
items.forEach(function(item) {
  widget.addNumberToItself(item);
});
pending…
Array.forEach() 2
items.forEach(widget.addNumberToItself, widget);
pending…
custom forEach (bind)
items.customForEachWithBind(widget.addNumberToItself, widget);
pending…
custom forEach (apply)
items.customForEachWithApply(widget.addNumberToItself, widget);
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.

0 Comments