One thing that all of the runtime performance tests here miss is another major consideration:
Network bandwidth.
Caching $(this)
into a local variable will generally decrease the size of your script, especially when minified (because this
cannot be reduced from four characters).
Consider:
function hello(text) {
$(this).attr();
$(this).css();
$(this).data();
$(this).click();
$(this).mouseover();
$(this).mouseleave();
$(this).html(text);
}
hello('Hello world');
Closure compiler's minified output is
function hello(a){$(this).attr();$(this).css();$(this).data();$(this).click();$(this).mouseover();$(this).mouseleave();$(this).html(a)}hello("Hello world");
This saves 39 bytes (20%). Now consider:
function hello(name) {
var $this = $(this);
$this.attr();
$this.css();
$this.data();
$this.click();
$this.mouseover();
$this.mouseleave();
$this.html(name);
}
hello('Hello world');
The minified output is
function hello(b){var a=$(this);a.attr();a.css();a.data();a.click();a.mouseover();a.mouseleave();a.html(b)}hello("Hello world");
This saves 74 bytes (37%), nearly doubling our byte savings. Obviously, real world savings in large scripts will be lower, but you still stand to gain significant reductions in the size of your script by caching.
Really, there's only an upside to caching $(this)
. You get miniscule but measurable runtime performance gains. More importantly, you can reduce the number of bytes that travel over the wire, and that directly translates to more dollars because faster page loads equal more sales.
When you look at it that way, you could actually say there's a quantifiable dollar cost to repeating $(this)
and not caching it.