views:

68

answers:

5

I use jQuery.

I have been reading a lot about selector performance and optimizing our AJAX app. I am looking to improve my selector performance. I know all the jquery performance tips. I haven't found an exact answer to a question I have. I am using almost every current jquery performance tip and yet my app still seems to lag quite a bit.

So, to optimize I am starting with selectors.

My question is: Is descending from a context to target an id faster than just targeting the id? I can't tell much of a difference.

Example:

Is

$('#childId', $higherElm);

faster than just

$('#childId');

????

Thanks in advance.

+1  A: 

According to this article, it's faster to have fewer, more direct selectors. #id is better than #id #child, at least in css...

hookedonwinter
A: 

When you're selecting by "id", context doesn't matter much because the engine's going to call getElementById() anyway. Context semantically matters of course, but that check should be pretty fast. (I suppose that in that light, having the context should be slightly slower, but you can't stop doing that if it's got actual meaning for your pages.)

Pointy
A: 

Not sure if the syntax you describe above would be beneficial, but on http://www.artzstudio.com/2009/04/jquery-performance-rules/ it does state in rule #5 that using sub-queries is faster (which makes sense)... they demonstrate it using the $higherElm.find() syntax, though.

In your example - since it maps directly to getElementById which is a native function call - I don't think you'll see much of an improvement. However, selectors that target sets of elements (hence looping), would probably see some, or major, benefit.

kander
@kander: they are faster when seeking out less specific elements. when seeking an element by id, `getElementById` is blazing fast, and the context just gets in the way.
Alexander Gyoshev
+2  A: 

As seen in the jQuery source, $('#id') does simply document.getElementById, while $('#id', context) does $(context).find('#id'). So the first is faster.

Alexander Gyoshev
Yes. Additionally, since `$('#id', context)` always ends up calling `$(context).find('#id')` (or maybe even `context.find('#id')` if `context` is already a jQuery object - not sure/can't remember, but it doesn't change the following...) you can just use the `$.find()` version for slightly more speediness.
Matt Ball
+1  A: 

Selecting an ID is the absolute fastest selection you can do.

Adding anything else will just slow it down.

Mark