LA.NET [EN]

Sep 25

 

One of the things people don’t do (most of the time) is use variables. For instance, here’s a snippet which shows some code which looks good:

function do1() {
    var time = (new Date).getTime();
    for (var i = 0; 
i < document.getElementById("content").childNodes.length;
i++) { var txt = document.getElementById("content")
.childNodes[i].innerText;
//do something } var end = (new Date).getTime() - time; alert(end); }

This codes works perfectly, ie, it will successfully go through all the child nodes of some element and it will get their text. The problem here is that using DOM for getting stuff is (kind of) expensive. On the other hand, variables are really cheap. What this means is that if you’re going to be using some element a lot, you should probably cache it in a local variable. Here’s an improved version of the previous function:

function do2() {
    var time = (new Date).getTime();
    var nodes = document.getElementById("content").childNodes;
    for (var i = 0; i < nodes.length; i++) {
        var txt = nodes[i].innerText;
    }
    var end = (new Date).getTime() - time;
    alert(end);
}

Yes, you end up writing more code. However, notice that we’re caching more aggressively here (ex.: the child nodes are cached and that means, for example, that we don’t have to go through the DOM during the for’s guard test). Oh, in case you’re asking, the answer is yes: we could still improve our code by caching the total count of child nodes and using that variable in the for’s guard.

Moral of the story: variables are cheap. prefer them over constant access to the DOM model.

3 comments so far

  1. Bertrand Le Roy
    9:12 pm - 9-25-2009

    Make it even faster by caching the length of the node collection, otherwise it gets reevaluated at each iteration.

  2. luisabreu
    11:28 pm - 9-25-2009

    Yep, that”s what I was trying to say with “we could still improve our code by caching the total count of child nodes and using that variable in the for’s guard.”

  3. Bertrand Le Roy
    1:01 am - 9-26-2009

    OOps, I missed that part. Apologies about that. I”ll shut up now :)

Leave a Reply

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


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>