Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is optimizing JavaScript for loops really necessary?

I read that it is advised to optimize loops in JavaScript by not reading the length attribute of an array every iteration in the loop header.

So, we should rather do this:

var names = ['George','Ringo','Paul','John'];
for(var i=0,j=names.length;i<j;i++){// Read array length once and assign it to a variable
    doSomeThingWith(names[i]);
}

instead of this:

var names = ['George','Ringo','Paul','John'];
for(var i=0;i<names.length;i++){
    doSomeThingWith(names[i]);
}

However, I created a small testcase to compare the two techniques, but sometimes the first case was faster and sometimes the second one.

Which version would you recommend?

like image 692
fabb Avatar asked Aug 07 '11 16:08

fabb


People also ask

Why is loop optimization very important?

Loop optimization is most valuable machine-independent optimization because program's inner loop takes bulk to time of a programmer. If we decrease the number of instructions in an inner loop then the running time of a program may be improved even if we increase the amount of code outside that loop.

Are loops important in JavaScript?

JavaScript loops provide a quick and easy method of doing something repeatedly. They are used to repeat an action number of times without having to repeat the same line of code.

Are for loops slow in JavaScript?

Notes. You should never use “ for-in” to iterate over members of an array. Each iteration through this loop causes a property lookup either on the instance or on the prototype, which makes the for-in loop much slower than the other loops. For the same number of iterations, it could be seven-time slower than the rest.

Is for loop faster than Map JavaScript?

We all know that for loop are faster than for each or javascript function since under the hood of javascript functions might be using for loops or something else which I'm not sure.


2 Answers

First, I should say that this answer is written in 2011 and these things change over time (as browser interpreters optimize more and more things) so if you really want to know the current state of the world, you have to run tests on current browsers.

Run your own jsperf test on any version of IE. There you will see a consistent difference between the two methods or many other old browsers. You apparently only ran it on Chrome which is so fast and so optimized that there is a negligible difference between the two methods. On IE9 (which is likely way better than IE7 and IE8), the method which pre-caches the length is 31% faster.

A jsperf test designed for this question gives quantitative results on this question. In questions like this one should just go to jsperf to see what the real difference is rather than so much speculation.

It shows a difference in the browsers I tried that ranges from almost no difference to a pretty sizable difference depending upon the browser. In Chrome, there's almost no difference. In IE9, storing the length first is almost 50% faster.

Now, whether this speed difference matters to your scripts depends on the specific code. If you had a huge array that you were looping through frequently, it could make a meaningful difference in some browsers to use this form:

for (var i = 0, len = list.length; i < len; i++) {
    // do code here
} 

In a slightly different test case when using live pseudo arrays returned by some DOM functions, there was still a difference in speed, but not as magnified (I expected the difference to be greater on DOM pseudo live arrays, but it wasn't).

In practice, I tend to use the short version (less typing) when I don't think my section of code is speed critical and/or the array is not large and I would use the longer version that pre-caches the length if I am consciously thinking about speed or the array is huge or I'm doing a lot of iterations over the same array.

There are a couple other programming reasons to pre-cache the length. If you will be adding elements to the end of the array during the loop and you don't want to the loop to iterate over those newly added elements, then you will NEED to pre-load the length and only iterate over the initially present elements.

for (var i = 0, len = list.length; i < len; i++) {
    if (list[i] == "whatever") {
        list.push("something");
    }
} 

Keep in mind that browsers are continually evolving and adding more and more optimizations so an optimization that shows great benefit in 2011 may be essentially built into a more modern browser in the future so the hand coded optimization is no longer needed. So, if you're trying to optimize something for today's performance, you have to test in today's browsers, you can't just rely on things you read that may be a few years old.

like image 196
jfriend00 Avatar answered Nov 15 '22 19:11

jfriend00


This advice was always a micro-optimization at best, and with all of the work being done on the speed of Javascript engines, it's unlikely to be a measurable difference any more. Perhaps somewhere in a very long very tight loop it might make a difference, but I doubt it.

For some reason, programmers tend to focus on speed above all else, even when it is unwarranted. Think about correctness, then readability.

like image 34
Ned Batchelder Avatar answered Nov 15 '22 19:11

Ned Batchelder