fastest while loops

JavaScript performance comparison

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

Info

Forked from Fastest array loops in Javascript #32, seemed 'while' loops far outstripped 'for' loops. Now, not so sure...

v4; + arr.length assignment inside for() - for() backwards; slowest for certain

Preparation code

<script>
  // Populate the base array
  var arr = [];
  for (var i = 0; i < 1000; i++) {
    arr[i] = i;
  }

  //called inside loops
  function someFn(ix) {
    return ix * 5 + 1 / 3 * 8;
  }
</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
While len--
var l = arr.length;
while(l--) { //counts backwards from max to 0, assumes dense array
  someFn(arr[l]);
}
pending…
Ordered while len--
var l = arr.length,
    i = l - 1;
while(l--) {
  someFn(arr[i-l]); //now loop is from bottom-up
}
pending…
While --len
var l = arr.length;
while(--l) { //counting backwards with backwards notation
  someFn(arr[l]);
}
pending…
For l outside
var l = arr.length;
for(var i = 0; i < l; i++){
  someFn(arr[i]);
}
pending…
For l inside
for(var i = 0, l = arr.length; i < l; i++){
  someFn(arr[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:

2 comments

tomByrer (revision owner) commented :

Results notes: The first 3 tests on Android 4.1.2 & first 4 test on Chome Mobile 26.0.1410 (actually is Opera Mobile beta 2013-04-04) are on the same Samsung Note 2 Sprint USA: 'UserAgent  For l inside  For l outside  Ordered while len--  While --len  While len--  # Tests  Android 4.1.2 80,313 82,195 78,654 81,031 81,908 3 Chrome Mobile 26.0.1410 34,253 36,882 28,795 34,792 28,898 4'

  • The gap between For vs While is much greater on desktops.
  • In the For loops, the outside length assignment only seems to benefit my phone, but has 0 effect on any desktop browsers.

tomByrer (revision owner) commented :

  • While is faster than For on IE8, but all tests were horribly slow vs Firefox 19 & Chrome 24 on the same Win7 i7 machine.

Add a comment