Don't overuse $(this)
If you're going to access the $(this) a lot, you might want to consider storing it into a local variable. So instead of something like this:
$('.items').each(function() {
var pos = $(this).offset();
var prevFloat = $(this).css('float');
var prevZIndex = $(this).css('z-index');
$(this).fadeOut();
...
You might want to consider changing your code to something more like this
$('.items').each(function() {
var $this = $(this),
pos = $this.offset(),
prevFloat = $this.css('float'),
prevZIndex = $this.css('z-index');
$this.fadeOut();
...
This will increase performance speed so you don't need to repeatedly create new jQuery objects
And as brombomb mentioned using $ infront of the variable name denotes that it's already a jQuery object
Written by Mark Vaughn
Related protips
14 Responses
I've done this for years. Why haven't I come up with the idea of writing this protip?
@hannesg I didn't even check if someone else previously posted it, I just keep running into this on open source projects, I was thinking it was worth mentioning again
Great tip, but it can very well apply to all look-ups. If you're repeating the same selector on every line, just cache it on a variable and reuse the object returned the first time.
Also don't overuse var keyword ;)
var $this = $(this),
pos = $this.offset(),
prevFloat = $this.css('float'),
prevZIndex = $this.css('z-index');
@idered hehe, true, I copy pasted this code directly from a jQuery plugin to make my point.
Also worth noting the idea of adding the $ to this to denote it is already a jquery object.
I'd say this is a rather micro-optimization.
http://jsperf.com/jquery-this-caching
Don't overuse $(this)
, but do understand this
and what it scopes to when you do use it :)
boys you optimization is funny. read how real men optimize http://msdn.microsoft.com/en-us/magazine/gg622887.aspx
@leoj3n in JavaScript (unlike PHP) the $ sign is an ordinary symbol when used in a variable name, just like a letter or an underscore. It doesn’t change anything as far as the interpreter is concerned. For programmers, it can be a useful way to identify variables that hold jQuery objects, like @brombomb mentioned.
@francisc I think you're example test it too simple. Of course it's not going to matter in an example where there is only one element the DOM. When you use $(this)
it starts from the root node and then checks every node until it finds the given selector. In a real world scenario the lookups could become more expensive.
This applies to everything that involves repetition. It's called the DRY (Don't Repeat Yourself) principle.
measure things before you say what exactly optimised and how much it is
@lublushokolad I like the 'real men' stuff!