Created
December 15, 2017 22:08
-
-
Save victoriachuang/38fbe16dd1ef38c103c5c209c83f0802 to your computer and use it in GitHub Desktop.
For loop optimizations
This file contains 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
// Here I'll demonstrate an easy way to optimize a for loop | |
// Here, I'm setting the for loop's condition as i < stringToPrint.length | |
// Totally valid, but each time I loop back to the beginning, I check whether | |
// the condition is true, which means I'll have to re-evaluate the value | |
// of stringToPrint.length, which is unchanging. This is inefficient, because | |
// I'll have to do this as many times as the string is long. | |
const originalLoop = () => { | |
const stringToPrint = 'Hello world'; | |
for (let i = 0; i < stringToPrint.length; i++) { | |
console.log(stringToPrint[i]); | |
}; | |
}; | |
// Instead, I can make stringToPrint.length a constant. This way, I only | |
// need to evaluate its value once. | |
const optimizedLoop = () => { | |
const stringToPrint = 'Once more, with feeling!'; | |
const stringLength = stringToPrint.length; | |
for (let k = 0; k < stringLength; k++) { | |
console.log(stringToPrint[k]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment