views:

252

answers:

3

I'm reviewing a number of jQuery functions that have various implementations of id selection. I want to try and standardise on one best-practice approach, but before I do that I want to ensure that I pick the most efficient.

Does anyone have links to good articles (such as this one) that make comparisons between different types of selections in jQuery?

Specifically, I'm after comparisons like $("#id"), $("#id[type=form_input_type]"), $("#id .class") and so on.

Actually, to be even more specific, my first priority is comparing:

$('input[id$="mySelectionID"]')

against

$('input:checkbox')

Both will return the same set of checkboxes. My gut feeling is that the second is faster, but I need to be sure.

A: 

Well, for selecting IDs, $("#id") will always be the most efficient, because it calls document.getElementById() directly with no extra method calls. Anything else will require more work on jQuery's part (such as class selection).

Salty
Yeah, actually I probably shouldn't have mentioned that one. The ID is always fastest - it's the comparison between others that I'm primarily interested in. There will be things that are dead slow to do (such as selecting by class) but the less obvious ones are what I'm really after.
Phil.Wheeler
+1  A: 

Slickspeed gives various performance figures for selectors across multiple js libs.

This test just compares various jQuery versions.

Mr Resig has an interesting post here regarding selectors.

redsquare
+1  A: 

In your examples you use the ID selector:

$("#id"), $("#id[type=form_input_type]"), $("#id .class")

An element id must be unique, if you use the id selector, you don't need to specify any more, because it matches a single element with the given id attribute.

Check this article about jQuery selector performance:

CMS
Excellent! I'd found that article a while back but couldn't remember where and hadn't been able to find it again. Thanks.
Phil.Wheeler
The results in the article are outdated though (older browser versions, older jQuery version). Here's the same set of tests using latest jQuery - http://jsbin.com/udaka
Chetan Sastry