jQuery Selector Specificity
I am just learning jQuery and I have been unable to find anyone specifically address this question.
For performance, would it be better to select $('#element') or $('div#eleme开发者_Go百科nt')? Does it make a difference?
Just use #id.
You can test this roughly using firebug console.
The results are emphatic.
nodeName#nodeId = 0.703ms (14 method calls)
#nodeId = 0.095ms (4 method calls)
(source: gyazo.com)
It is a best practice to not place the tag name before an ID.
ID lookups use the native getElementById()
and are extremely fast, so any additional comparison that is not required will just slow down the selector.
So generally, use $('#myID')
instead of $('div#myID')
.
The performance difference is minimal, but that is the case for many best practices.
Probably the only time when this may be necessary would be when you are using the same javascript file for 2 different pages where the same ID is used in the two pages but on different types of tags. Then you would need the specifier.
If that's the case, you'll be better off adjusting your IDs.
Yes, it can make a difference. Like in css, try to be keep things as non-specific as possible.
The differences are probably minimal, but when in doubt, profile in Firebug.
I'll grab you a reference shortly.
Edit
I can't find a quick reference of speed tests, but this is probably one of those premature optimizations that isn't worth worrying about, especially using IDs. I think the sizzle engine is quite good at sorting that out.
It may be more of an issue in more complex selectors involving tags and classes. Again, profile!
Edit #2
I should have looked at the docs! yes, it does make a difference - an additional lookup is required.
http://api.jquery.com/id-selector/#id
And their great quote:
As always, remember that as a developer, your time is typically the most valuable resource. Do not focus on optimization of selector speed unless it is clear that performance needs to be improved.
If you assume this:
<span id="element"></span>
<div id="element"></div>
$("#element")
will select both, while $("div#element")
will get only the div, it's more specific.
精彩评论