Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 807
Pavlo Avatar asked Dec 17 '12 17:12

Pavlo


1 Answers

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

like image 50
T.J. Crowder Avatar answered Oct 12 '22 23:10

T.J. Crowder