开发者

How much overhead is there when traversing the DOM?

(I'm using prototype.js here, but I imagine the same holds true across other libraries as well)

I often find myself writing code like this:

var search_box;

Event.observe(window, 'load', function() {
    search_box = $('search_box');
});

function doSomething(msg) {
    search_box.innerHTML = msg;
}

Rather then writing it simply like this:

function doSomething(msg) {
   $('search_box').innerHTML = msg;
}

My开发者_如何转开发 intention is to avoid having to traverse the entire DOM searching for the "search_box" element everything I need access to it. So I search for it once on page load and then stick the reference in a global variable. However, I don't recall ever seeing anyone else do this? Am I needlessly making my code more complex?


This is called premature optimization.

You are introducing a global variable to optimize something you have not profiled.

Your assumption that the $ "traverses the DOM" is incorrect. This function is implemented using document.getElementById which is the fastest way to access an element in the DOM.

I suggest coding your javascript using basic programming best practices such as avoiding global variables, and not optimizing without profiling. Once your application is working as expected, then you should profile it (using firebug) and address the area(s) where it is slow.


I usually do the same thing, the reason you don't see it often is probably because you don't see well written code often that's optimized ( nevermind the whole preoptimization is evil thing ) - I say if you can optimize it without headaches then why not?

Realistically speaking though that's a very very trivial DOM lookup, you should only begin to worry if you're iterating through dozens of elements and being vague in the selectors.. so I wouldn't worry too much about it unless you can really notice certain parts of your web page loading rather slowly, in which case you should store the multiple elements you access in the outer scope's variable.

Good:

(function() {

var els = $$('.foo span'); // also better to specify a context but I'm not sure how that's done in Prototype, it's the second param in jQuery.

function foo() {
   els.something();
}

els.somethingElse();

})();

Bad:

(function() {

var els = $$('.foo span'); // also better to specify a context but I'm not sure how that's done in Prototype, it's the second param in jQuery.

function foo() {
$$('.foo span').something();
}

$$('.foo span').somethingElse();

})();


I decided to spend a bit of time doing some testing to get some hard data. The answer is that preloading the elements into global variables is twice as efficient as accessing them using the DOM getElementById method. (At least under FF 3.6).

Subsequent accesses to the objects is also more efficient using the global variable method, but only marginally so.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜