views:

101

answers:

2

In a particular script I'm writing, I have a number of objects which are linked to some DOM Elements. Given that each element has a unique id, should each object keep just the element's id (and use document.getElementById each time), or store the element in a property?

Here's a simplified example of what I mean:

function myThing(elId) {
    this.elId = elId;
}
myThing.prototype.getElValue = function() {
    return document.getElementById(this.elId).nodeValue;
};

// -- vs -- //

function myThing(elId) {
    this.el = document.getElementById(elId);
}
mything.prototype.getElValue = function() {
    return this.el.nodeValue;
};

Does it make any difference? Are there any performance issues I should know about?

+3  A: 

Store the element not the id, the look up is slow and expensive and saves you a function call. I think a simple test would confirm this.

apphacker
+4  A: 

I would store the element; it tends to make code clearer when you're not calling document.getElementById all the time, and though in your case you may not need to change IDs or allow elements without IDs, it's pretty common to want to do so.

(Unlike apphacker I wouldn't expect huge efficiency improvements from doing so, as getElementById tends to be fairly well-optimised in browsers.)

Are there any performance issues I should know about?

References from JavaScript objects to DOM objects are fine on their own, but when a DOM object has a link back to such a JavaScript object (usually through an event handler), you've got a reference cycle. This causes IE6-7 to leak memory as it fails to free up the cycled objects. For small simple apps you may not care. For complicated, long-running apps, you might have to work around the problem, for example by indirecting every event handler through a lookup map/array so there is no direct reference from the DOM object to the real event handler.

bobince