JavaScript Perfromance Tip- Don’t Test Against obj.length. Test Against a Local Variable.

I saw it yesterday in some code I was debugging and I realized I’ve become hyper sensitive to this common pattern:

var anchors = document.getElementsByTagName('a');
if (anchors.length > 0){
    for (var i=0; i < anchors.length; i++) {
        addEvent( anchors[i], 'click',  trackLinks );
    };
};

Why am I sensitive to it? Well, what are some of the things we know about JavaScript performance?

  • Local variables are fast
  • DOM Methods are slow
  • The DOM Method getElementsByTagName returns a LIVE HTMLCollection.

Put those things together and you'll see that you're getting hit with a couple of performance penalties.

Firstly, even setting anchors to a local variable doesn't stop it from having to do another lookup against the entire document. To stop it from executing the lookup, you would need to copy the resulting NodeList into an Array and then manipulate the Array. In this situation it doesn't really matter since we're only looping through it once (which is what you'd have to do to pass it into an Array anyway.)

It's still interesting and important to keep in mind when using DOM methods like getElementsByTagName or getElementsByClassName.

Where it does matter in the above sample is with the two references to anchors.length. Each time that's referenced the lookup has to be performed again. That's costly. Especially when it could be set to a speedy local variable instead.

What we should do looks something like this:

var anchors = document.getElementsByTagName('a');
var test = anchors.length;
if (test > 0){
    for (var i=0; i < test; i++) {
        addEvent(anchors[i], 'click',  trackLinks );
    };
};

Speedtastic.

3 thoughts on “JavaScript Perfromance Tip- Don’t Test Against obj.length. Test Against a Local Variable.

  1. That’s a great page. The i-- stuff is interesting to me. maybe another post? I feel like that idea needs a little more explaining since it’s reversing a deeply ingrained pattern. I know about it and I have trouble remembering to try it.

Leave a Reply

Your email address will not be published. Required fields are marked *