HI Guys, I have a question,
Im trying fo find the most efficient way in terms of performance to store and access an element in the javascript protoype library.
lets say I dynamically create a parent with an child element in a test class
testclass = Class.create({
newParent: null, //I will create a global reference to the parent element
method1: function(){
this.newParent = new Element('div',{'id':'newParent'});
var elm = new Element('div',
{
'id': 'elm1',
'identifier': 'elm1identifier'
}
);
newParent.insert(elm);
},
method2: function(){
??????????
}
})
In method 2, I want to be able to access the element elm1.
I have been thinking, and here are my different solution.
-
I can access the element using the utility method provided by prototype $()
method2: function(){ $('elm1'); } -
I can make a global reference to the element.
elm1: null, .... method2: function(){ this.elm1 }
3.I can pass the element in the method as a parameter but this option will not always be available
-
I create a unique identifier as an attribute and use the protoype .down function
this.newParent.down('[identifier=elm1identifier]');
So ofcourse i use a combination of these, but im curious, at out of all the methods, which is the most efficient in terms of performance.
I heard that the $() utility method searches the whole dom? Is this a significant difference? What if you have alot of elements.
Storing references to elements may also cause memory problems especially if you have a lot of javascript in a big web site.
using a unique and custom identifier is also nice, but you also add new attributes which might have an effect on the dom itself. But this advantage is that you specifiy where you want to search using the element.down() method in prototype.
Thanks for the help guys.
If you are creating an object that is supposed to represent a DOM element, it seems sensible to give it a property that references the element, say “element”. Then in method1:
I think at this stage, micro-optimising for performance is pointless since the biggest improvement in performance would be to not use Prototype.js.
The $() method is firstly an alias for document.getElementById (which is blazingly fast in browsers and always has been) and secondly adds convenience methods to the element returned. If the browser doesn’t implement a prototype based inheritance scheme, Prototpye.js adds about 50 methods directly to the element as properties, which is a pretty expensive operation.
I doubt that storing references to elements will cause significant memory issues unless you are storing tens of thousands and not using them (they are just references after all).
Do not add custom attributes or properties to DOM elements. Prototype.js version 2.0 is going away from this model (at last), just don’t do it. If you have an object that represents (or “wraps”) an element, add the property to that.