JQuery object: cache or not cache?

I have some problems with my Javascript (JS) codes, as I sometimes have to access the same DOM elements more than once in the same function. Some arguments are also presented here .

In terms of performance, is it better to create a jQuery object once and then cache it, or is it better to create the same jQuery object on your own? Example:

function(){
  $('selector XXX').doSomething(); //first call
  $('selector XXX').doSomething(); //second call
  ...
  $('selector XXX').doSomething(); // n-th call
}

or

function(){
  var  obj = $('selector XXX');
  obj.doSomething(); //first call
  obj.doSomething(); //second call
  ...
  obj.doSomething(); // n-th call       
}

I suppose the answer probably depends on the value of "n", so suppose n is a "small" number (like 3), then an average (like 10) and finally big (like 30, like if the object is used for comparison in a cycle per cycle).

Thanks in advance.

+5
6

, n 1, ( $('#something').something().somethingelse(); jQuery, ). , , , $, , jQuery. , , var $content = $('#content');, $content.find('...'); .

+6

- . , . , , . , N .

-, , dom, .

+4

, .

. , . , . : , . , .

, , . , : jQuery . , DOM , , .

, , Chrome Heap Profiler . , , , , , IE, .

IMO, , , , , .

$(this), Nick Craver. , , , - .

+2

jQuery, , . ids, , . , , .

: $('table tr td') - . .find(), .

, , - , , .

var timer = new Date(); 
// code here
console.log('time to complete: ' + (new Date() - timer));

2 , , , .

+1

JavaScript , . . , , . , jQuery , null , , , . :

var createHandler = function (someClosedOverValue) {
    return function () {
        doSomethingWith(someClosedOverValue);
    };
}

var blah = function () {
    var myObject = jQuery('blah');

    // We want to enable the closure to access 'red' but not keep
    // myObject alive, so use a special createHandler for it:
    var myClosureWithoutAccessToMyObject = createHandler('red');

    doSomethingElseWith(myObject, myClosureWithoutAccessToMyObject);

    // After this function returns, and assuming doSomethingElseWith() does
    // not itself generate additional references to myObject, myObject
    // will no longer have any references and be elligible for garbage
    // collection.
}

jQuery(selector) DOM , , . , , , . I.e., DRY , WET.

jQuery . jQuery , , - - . DOM jQuery(DOMElement), .

, , , . , ; -).

0

All Articles