While vs For Queue vs Reduce

JavaScript performance comparison

Revision 43 of this test case created

Info

These test cases are an embarrassment. If code is "running" 200,000,000 times in a second then it's a no-op. Note that jsperf runs the "setup" code ONCE then the rest of the code N times.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var items = [], total = 0, i = 0, j = 0;
    for(;i<100000;i++) {
      items[i] = 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
for(j=0; j<items.length; j++) {
  total += items[j];
}
pending…
While
j = items.length;
while(j) {
  total += items[--j];
}
pending…
Do
j = items.length;
do {
  total += items[--j];
} while(j);
pending…
Reduce
total = items.reduce(function(i,c) { return c+i; }, 0)
pending…
ForEach
items.forEach(function(i) { total += i })
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