Pavlo
Pavlo

Reputation: 44889

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

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

Upvotes: 6

Views: 212

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074168

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. :-)

Upvotes: 9

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

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.

Upvotes: 3

Related Questions