JSPerf, For Loop vs While Loop
Ad
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
Ad
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
Related Questions
Ad
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad