Search code examples
javascriptperformancemootools

JavaScript/MooTools - Better to save element in object property vs. accessing each time with $('elem')?


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 $?


Solution

  • 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.