javascript loop optimization

JavaScript performance comparison

Revision 3 of this test case created by Zaheer Ahmed

Preparation code

<h3><a href='http://conceptf1.blogspot.com/2014/01/javascript-best-practices-loop-optimization.html'>JavaScript Best Practices : Loop Optimization </a></h3>
      
<script>
Benchmark.prototype.setup = function() {
  var i, max, fruits = ["apple", "banana", "orange", "mango"];

};
</script>

Preparation code output

<h3><a href='http://conceptf1.blogspot.com/2014/01/javascript-best-practices-loop-optimization.html'>JavaScript Best Practices : Loop Optimization </a></h3>

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
counter & condition to break within loop
for (var i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
pending…
Cache condition to break
for (var i = 0, max = fruits.length; i < max; i++) {
  console.log(fruits[i]);
}
pending…
cache counter and condition to break
for (i = 0, max = fruits.length; i < max; i++) {
  console.log(fruits[i]);
}
pending…
Without increment (i++) operator
for (i = 0, max = fruits.length; i < max; i += 1) {
  console.log(fruits[i]);
}
pending…
reverse loop
for (i = fruits.length; i -= 1;) {
  console.log(fruits[i]);
}
pending…
while without decrement operator
i = fruits.length;
while (i -= 1) {
  console.log(fruits[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.

1 Comment

angh commented :

This is quite bad, as last loops doesn't display 'apple', they ignore array[0]

JavaScript Best Practices : Loop Optimization