fastest while loops

JavaScript performance comparison

Revision 6 of this test case created by tomByrer

Info

Thanks to Jens Roland, this test bay be slightly more realistic than some others since the loop executes real code, & the array is larger (though still simple & dense). This test also assumes that you will re-use the same array elsewhere in your code, there are shortcuts you can use if you can consume/destroy the array.

v5

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;
  }

  var frag = document.createDocumentFragment();
</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 t = 0; //running total
var l = arr.length;
while(l--) { //counts backwards from max to 0, assumes dense array
  t += someFn(arr[l]);
}
//write results
frag.innerHTML = '<div>While len--: ' + t + '</div>';
document.body.appendChild(frag);
pending…
Ordered while len--
var t = 0;
var l = arr.length,
    i = l - 1;
while(l--) {
  t += someFn(arr[i-l]); //now loop is from bottom-up
}
frag.innerHTML = '<div>Ordered while len--: ' + t + '</div>';
document.body.appendChild(frag);
pending…
While --len
var t = 0;
var l = arr.length;
while(--l) { //counting backwards with backwards notation
  t += someFn(arr[l]);
}
frag.innerHTML = '<div>While --len: ' + t + '</div>';
document.body.appendChild(frag);
pending…
For outsides
var t = 0;
var i = -1, //NOTE init -1, since the 1st run starts i = 0
    l = arr.length;
while (++i < l){ //simple & forward
  t += someFn(arr[i]);
}
frag.innerHTML = '<div>For outsides: ' + t + '</div>';
document.body.appendChild(frag);
pending…
For outsides
var t = 0;
var i,
    l = arr.length;
for(i = 0; i < l; i++){
  t += someFn(arr[i]);
}
frag.innerHTML = '<div>For outsides: ' + t + '</div>';
document.body.appendChild(frag);
pending…
For insides
var t = 0;
for(var i = 0, l = arr.length; i < l; i++){
  t += someFn(arr[i]);
}
frag.innerHTML = '<div>For insides: ' + t + '</div>';
document.body.appendChild(frag);
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