Is there any performance gain from caching $ (this)?

I often use $(this) inside jQuery event handlers and never cache it. If i do

 var $this = $(this); 

and will use a variable instead of a constructor, will my code get significant additional performance?


JS Perf benchmark for measuring performance gains from this optimization: http://jsperf.com/jquery-this-caching

+6
source share
2 answers

A tiny tiny miniature inconspicuous , yes. Significant? Not.

Each time you execute $(this) , it calls several function calls and a couple of memory allocations. The function call does not exist either there or there (even on IE6, I was surprised to find out ), but memory junk can add up in browsers that manage memory very well. Most modern do.

I always save the result in a variable because I just don't like the calling functions and unnecessary selection of objects. And it allows you to print these parades. :-)

+9
source

Yes, because every time you do $(this) , you create a new jquery object.
But you won’t get significant performance, just if you do it over 1000x

And it is good practice to cache objects used more than once.

+3
source

All Articles