Skip to content →

jQuery Selector Performance – The This and That Test

There are many ways to select an element using jQuery. At some point, it usually starts with $(‘#id;) – from there, you have a lot of options, all of which can severely affect the performance of your script.

A common theme amongst new jQuery users (and myself, admittedly) is that you can continue to select the afore-selected element. Here’s an example:

[code]
$(‘#id’).click(function() {
$(‘#id’).fadeOut();
});
[/code]

A very simple example, but with expensive implications. Grabbing that #id again is pricey. But that only makes sense – making JS transverse the DOM once again to find your element is a costly task. That’s why a lot of developers, at least in some contexts, use “this” to remove that step.

[code]
$(‘#id’).click(function() {
$(this).fadeOut();
});
[/code]

Conventional web wisdom says that you’re going to get a performance increase because you’re skipping the DOM traversal step here – and that is correct. But this can be modified yet again:

[code]
var id = $(‘#id’);
id.click(function() {
id.fadeOut();
});
[/code]

This is caching the selector in the variable “id” – something that gets to the middle territory of coders as they progress through more complex JS tasks. But which of these is the fastest?

I created a jsPerf case for that very reason. With the help of a fellow Stack Overflower, we were able to produce a very interesting test case.

The “this” and cached methods are, predictably, faster – but what is even more surprising is the variance in performance on cached selectors on a per-browser basis. It is pretty much all over the board. But what does this tell us?

This test is a remark about the different JIT compilers per browser, and how they’re unique to each browser (and in some cases, each version). That’s obvious – what isn’t so obvious is the performance difference between the three tests across the different browsers. Something to consider when coding your next webapp!

Published in Uncategorized

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *