views:

95

answers:

1

In terms of speed/memory efficiency, does it make sense to save an element (retrieved via $) to a variable in an object or use $ to access it each time?

Does accessing object properties (especially if nested a few levels - object within object) perform faster than using $?

+4  A: 

caching selectors that are frequently used is always a good idea. namespacing behind a several levels deep object creates a longer than neccessary global scope chain, imo. I tend to cache selectors within simple closures or via using mootools' element storage.

for example, if you have a link in a div that locates the parent, then finds 2 elements down and the first img and you can see the user clicking it multiple times, you can do something like this:

document.id("somelink").addEvent("click", function() {
    var targetImg = this.retrieve("targetImg") || this.store("targetImg", this.getParent().getNext().getNext().getElement("img.close"));
    targetImg.fade(.5);
...
});

on the first click it will look up the target img and store it under the link's storage with key targetImg, any subsequent clicks will use the stored reference. mootools' storage that is created at the time of extending of the element and the assignment of a uid. is just a simple object behind a closure so it's not within a proprietary property on the element that will slow down access in IE etc and it's not in any window. property.

when you consider the philosophy of mootools coding in general - i.e. code with class - there are a few things that are (un)written best practices when writing a mootools class/plugin.

if it pertains to a single element, then set this.element = document.id(element); - store the reference. if it's an array, then similarly you do the caching this.elements = document.getElements(this.options.selector);

so, always store a reference to the main selector.

Dimitar Christoff
Thanks for the reply. So MooTools itself doesn't employ any kind of caching with $?
Andy Rey
not that i know of - and that is a good thing. imagine you reference $("foo") which becomes a pointer to the object. you then use ajax or dom manipulation to destroy the element or recreate it through re-writing the parent's html - you wouldn't want a reference to $("foo") to return the old element (and it's associated uid, events and so forth).the lookup through the selector is usually very fast anyway so there is no sense in storing it into a variable always, but you will notice the difference in animations that take place several or 10s of times a second. `if called more than once, cache`
Dimitar Christoff