Daily Archives: 27 February 2014

Cache Length in for{} Loop or Not

Sometimes things just aren’t the way they are meant to be.

I’ve been reading up on ways to improve the efficiency of my JavaScript. But then, when I do some benchmark testing, the results that come in are a little unexpected.

An example. According to JavaScript luminaries, when you are iterating in a for loop, you can improve performance by using a variable to store the length of whatever collection you are iterating.

for (var i = 0, l = collection.length; i < l; i++) {
    a.num += collection[i];
}

/************* INSTEAD OF *************/

for (var i = 0; i < collection.length; i++) {
    a.num += collection[i];
}

The idea being, that if you don’t have to look up the length variable of the collection in every iteration, then it should run much faster.

Consider this benchmark test that I have created at jsperf.com

The interesting results for Chrome and Firefox were that the difference is negligible (in fact, in some tests the non-cached variable test was quicker). In IE 11, the expected result was reached.

It seems that Chrome and Firefox have built into their AJAX engines some kind of optimisation which is invoked when it sees the for loop structure and does not do the look-up on every iteration.

Of course, there may be something in my test which is not correct and causing the anomaly. I’d be interested in feedback if people think my test could have been written in a better manner. I saw some other tests which called Console.Log() in each iteration of the loop. I thought that was a bad idea as calling that method is probably pretty expensive and would result in bad result data, insofar as the differences would not be discernible owing to the large amount of time taken in each iteration for both types of test.

So I guess the question is, if the browsers compensate for sloppy Javascript, do we need to burn the calories to learn all those optimization tricks? I think so. Just because.