So i have been taking a Computer science course that uses C+ to teach programming concepts with. today i learned a new concept that i was not sure applied to JS, in which there are system resources expended each time a string.length is calculated. It seems like a tiny matter but it got me thinking about huge arrays and how that could add up. Check out this example and let me know if loop #2 is indeed more efficient than the first and thanks:
var weekDay = ["Monday", "Tuesday", "Wednesday"];
//for loop #1
for(i=0; i<weekDay.length; i++){
//code code code
;}
//for loop #2
for(i=0; var n=weekDay.length; i<n; i++){
//code code code
;}
The second approach is faster, but not by much. Also, there is a small syntax error
This is rather common in javascript code. Please note the importance in declaring all of your variables with
varso that they do not step on the wrong scope.You can see this js performance test here: http://jsperf.com/forloopiterator which shows the results being 24% faster when using the second approach.