Selectors: Id vs. Context

I am using jQuery.

I read a lot about selector performance and optimizing our AJAX application. I want to improve the selector. I know all the jquery performance hints. I did not find the exact answer to the question that I have. I use almost all of the current jquery performance hints, and yet my application is still slightly behind.

So, for optimization, I start with selectors.

My question is: does it get out of context to target an identifier faster than just aiming an identifier? I can not say anything significant.

Example:

there is

$('#childId', $higherElm); 

faster than just

 $('#childId'); 

????

Thanks in advance.

+4
source share
5 answers

As can be seen from the jQuery source , $('#id') does just document.getElementById , and $('#id', context) $(context).find('#id') . So the first one is faster.

+3
source

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

+1
source

Choosing an ID is the quickest choice you can make.

Adding everything else will just slow it down.

+1
source

When you select "id", the context is not a big deal because the engine will call getElementById() anyway. Of course, the context is semantic, but this check should be pretty quick. (I believe that in this light, the context should be a little slower, but you cannot stop doing it if it gets the actual value for your pages.)

0
source

I'm not sure if the syntax described above would be useful, but at http://www.artzstudio.com/2009/04/jquery-performance-rules/ rule 5 says that using sub -queries is faster (which makes sense) ... they demonstrate this using the syntax $ higherElm.find (), though.

In your example - since it maps directly to getElementById, which is a function-based call - I don't think you will see much of the improvement. However, selectors that target multiple elements (hence looping) would probably see some or main advantages.

-1
source

All Articles