While vs For Queue vs Reduce

JavaScript performance comparison

Revision 47 of this test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var items = [], total = 0, i = 0, j = 0;
    for(;i<100000;i++) {
      items[i] = { num: Math.ceil( Math.random() * 10 ) };
    }
};
</script>

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
For
total = 0;
for(j=0; j<items.length; j++) {
  total += items[j].num;
}
pending…
While
j = 0;
total = 0;
while(j < items.length) {
  total += items[j].num;
  ++j;
}
pending…
Do
j = 0;
total = 0;
if (items.length > 0)
  do {
    total += items[j].num;
    ++j;
  } while(j < items.length);
pending…
Reduce
total = items.reduce(function(c, item) { return c + item.num; }, 0);
pending…
ForEach
total = 0;
items.forEach(function(item) { total += item.num });
pending…
For (reverted)
total = 0;
for(j = items.length-1; j >= 0; j--) {
  total += items[j].num;
}
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