Ad

JSPerf, For Loop Vs While Loop

Hey guys can anyone tell me why my code in this JSPerf seems to indicate that a for loop is actually faster than a while loop?

I even decrease the value toward zero, and for still seems to outperform?

http://jsperf.com/html-canvas-performance

For the record, I'm making an HTML / Canvas game and I need to iterate through entities for rendering purposes.

EDIT : Code - EDIT In case it's not clear what the problem is; " for still seems to outperform?"

  Benchmark.prototype.setup = function() {
    var e = [];
    var i = 100;
    while(i--) e.push(Math.random() * -1 << 1);
  };

  Benchmark.prototype.teardown = function() {
    e.length = 0;
  };

//WHILE
var i = e.length;
while(i--) e[i] *= 123;

//FOR
for(var i = 0; i < e.length; i++) e[i] *= 123;
Ad

Answer

Looks like accessing array backwards is slow, but not because of while.

http://jsperf.com/html-canvas-performance/3

same performance with following code for me.

var i = 0, z = e.length;
while(i < z) e[i++] *= 123;
Ad
source: stackoverflow.com
Ad