for vs forEach vs loop

JavaScript performance comparison

Revision 164 of this test case created by Dmitry Khlestkov

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  
  const arr = [];
  for(let i = 0; i < 100; i++) {
    arr[i] = {
      val: i,
      bool: Boolean((i % 3))
    };
  }
  
  consr values = [];

};
</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
standard for + let
for(let i = 0, l = arr.length; i < l; i++){
  if (arr[i].bool) {
    values.push( arr[i].val );
  }
}
pending…
for of
for(const itm of arr){
  if (itm.bool) {
    values.push( itm.val );
  }
}
pending…
standard for with caching
for(var i = 0, l = arr.length; i < l; i++){
  var itm = arr[i];
  if (itm.bool) {
    values.push( itm.val );
  }
}
pending…
standard for
for(var i = 0, l = arr.length; i < l; i++){
  if (arr[i].bool) {
    values.push( arr[i].val );
  }
}
pending…
Array#forEach
arr.forEach(function(value) {
  if (value.bool) {
    values.push(value.val);
  }
});
pending…

Revisions

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

0 Comments