Skip to content

Instantly share code, notes, and snippets.

@lastobelus
Last active January 21, 2016 03:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lastobelus/c6b08b86d290b4d01e35 to your computer and use it in GitHub Desktop.
Save lastobelus/c6b08b86d290b4d01e35 to your computer and use it in GitHub Desktop.
Quick and dirty benchmarks of for vs negative while loop in javascript
var i = 100000;
var myArray = [];
while(i--) myArray[i] = i;
myArray[0];
console.log("------- for loop always evaluating length-------")
var forResult = 0; console.time("for"); for(var i=0; i < myArray.length; i++) { forResult += myArray[i] }; console.log("forResult: %i", forResult); console.timeEnd("for");
console.log("------- for loop with length in var-------")
var forResult2 = 0; console.time("for2"); for(var i=0, len = myArray.length; i < len; i++) { forResult2 += myArray[i] }; console.log("forResult2: %i", forResult2); console.timeEnd("for2");
console.log("------- negative while loop -------")
var whileResult = 0; console.time("while"); var j = myArray.length; while(j--) { whileResult += myArray[j] }; console.log("whileResult: %i", whileResult); console.timeEnd("while");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment