3

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
;}
Travis J
  • 81,153
  • 41
  • 202
  • 273

4 Answers4

5

The second approach is faster, but not by much. Also, there is a small syntax error

for( var i = 0, n = weekDay.length; i < n; i++ ){ ... }

This is rather common in javascript code. Please note the importance in declaring all of your variables with var so 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.

Travis J
  • 81,153
  • 41
  • 202
  • 273
2

First of all, premature optimization is the root of all evil.

Secondly; you are completely correct that loop #2 is more efficient.

Loop #1 would do calculate the length of weekDay for every iteration of the loop. This means it would calculate the length 10,000 times in a 10,000 length array.

Loop #2 would calculate the length of weekDay and set the variable n to be the result, and hence we keep the length in a variable rather than recalculating it for every iteration.

Read more about why premature optimization is bad.

Community
  • 1
  • 1
h2ooooooo
  • 39,111
  • 8
  • 68
  • 102
  • 2
    Technically array.length doesn't calculate the length. The length is calculated per addition / deletion so .length only gets the stored value. – Ash Burlaczenko Jan 09 '13 at 10:40
0

This question has been asked a few times... Is optimizing JavaScript for loops really necessary?

I found the following link very helpful. Basically it depends on browser version and vendor.

In some cases e.g. IE yes #2 is much faster

http://jsperf.com/loop-iteration-length-comparison-variations

Community
  • 1
  • 1
wmitchell
  • 5,665
  • 10
  • 37
  • 62
0

I would always pre-cache the length explicity, i.e.

var n = weekDay.length;
var i;
for(i=0;i<n; i++){ 
do_something;
}

A much clearer approach, as all variables definitions are 'hoisted' to the top of the function anyway.

Karl
  • 13
  • 2
  • 3