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
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. 🙂