Last active
January 21, 2016 03:48
-
-
Save lastobelus/c6b08b86d290b4d01e35 to your computer and use it in GitHub Desktop.
Quick and dirty benchmarks of for vs negative while loop in javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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