Does creating and reusing a reference increase performance appreciably when the selector is $(this)?
I create references for my jQuery selectors when I use the same selector multiple times in the same scope. The following is more efficient
var jSel = $('div.some_class input.some_other_class');
some_function1(jSel);
some_function2(jSel);
than this
some_function1($('div.some_class input.some_other_class'));
some_function2($('div.some_class input.some_other_class'));
But what if the selector is simply $(this) where this is a dom element inside a jQuery method. Should I bother to create a reference to $(this) and reuse the reference or can I create multiple $(this) selectors and expect similar performance?
Is the following
var jSel = $(this);
some_function1(jSel);
some_function2(jSel);
significantly faster than the following?
some_function1($(this));
some_function2($(this));
No. It is microscopically faster; in the realms of just a few microseconds.
Does that stop you assigning the result to a variable and using that? No. Using a variable can give more meaning to what
thisis, and can be easier to type. Plus, if you stopped wanting to operate on$(this), and instead wanted$(this).next(), you have to change it in one place instead ofn.You’ll find the jQuery constructor is highly optimized for accepting a single DOM element as a parameter. The following is the exact code that gets executed when you call
$(DOMElement)(after the jQuery object has been created, of course):