Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does jQuery $(this) need to be cached

I recently came accross some blog posts about jQuery performance (i.e. http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performance/) and it was stated in all of them that we should cache the jQuery objects to javascript variables.

What I need to know, though, is if this applies to $(this) as well. Am I going to gain in performance if I do this:

$("#some-link").click("click", function(){
  var $this = $(this);
  $this.doSomeThing();
});

Thank you in advance for your help.

like image 462
dizzy_fingers Avatar asked Dec 08 '22 05:12

dizzy_fingers


1 Answers

this may refer to many different objects.

Caching $(this) may not be important, because this is already the current element and thus jQuery does not need to search the DOM for this element.

However in a single function if you have more than one times calling $(this), it is wise to put $(this) to a variable instead of calling $(this) many times.

$("#some-link").click("click", function(){
  var $this = $(this);
  $this.doSomeThing();
  $this.doThisThing();
  $this.doThatThing();
});

would be more efficient than

$("#some-link").click("click", function(){
  $(this).doSomeThing();
  $(this).doThisThing();
  $(this).doThatThing();
});
like image 68
mauris Avatar answered Dec 30 '22 00:12

mauris