6

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

var $this = $(this);

and will use variable instead of the constructor, will my code get any significant extra performance?


JS Perf test to measure the performance gain from this optimization: http://jsperf.com/jquery-this-caching

Pavlo
  • 43,301
  • 14
  • 77
  • 113
  • That depends on how frequently it is used. `$(this)` constructs a new jQuery object, and everything that goes with it. Generally if you are going to use `$(this)` more than once in a block of code, you should cache it. Especially if you are doing it in a loop. – Shmiddty Dec 17 '12 at 17:53
  • 1
    It's always going to be faster to cache `$(this)` in a var. It's micro-optimization to be sure. You definitely need to be caching any selectors, because that has much bigger implications. – Dominic Barnes Dec 17 '12 at 17:54
  • If you evaluate it 100 times within the same call stack, you may get 1, or 2 milliseconds slower execution. – Šime Vidas Dec 17 '12 at 17:55
  • More good answers: http://stackoverflow.com/questions/10433014/what-is-the-cost-of-this – Pavlo Aug 21 '13 at 10:33

2 Answers2

9

A teeny tiny miniscule imperceptible one, yes. Significant? No.

Every time you do $(this), it results in several function calls and a couple of memory allocations. The function calls are neither here nor there (even on IE6, I was surprised to learn), but the memory churn could add up on browsers that don't handle memory management very well. Most modern ones do.

I always save the result to a variable, because I just don't like calling functions and allocating objects needlessly. And it saves typing those parens. :-)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 2
    I just apply the same rule I do in all my other programming. If I'm calling the same function more than once within a function, I cache the result so I don't have to call it more than once. `$()` is a function call. Been using that as a guideline for 30 years. – jfriend00 Dec 17 '12 at 17:56
  • @jfriend00: Yeah, me too (and a surprisingly similar period of time...). – T.J. Crowder Dec 17 '12 at 18:00
3

Yes, because everytime you do $(this) you create a new jquery object.
But you won't get a significant performance, just if you do it more than 1000x

And it's a good practice to cache objects used more than once.

Ricardo Alvaro Lohmann
  • 26,031
  • 7
  • 82
  • 82