开发者

CSS and jQuery Selector Speed

In jQuery whenever I encounter something like this:

$("div#MyDiv").....

I generally say to the developer: "Don't bother putting the div in front of #MyDiv, ID selectors are the fastest." I.e.

$("#MyDiv")....

This is because the latter will hook directly into document.getElementById rather than having to scan the DOM for all <div> elements first.

My question is, do the same rules apply to CSS selectors? I.e. rather than:

div#MyDiv
{
}

Is it faster to have simply?:

#MyD开发者_如何学Goiv
{
}

(I realise that CSS selectors are incredibly fast anyway, so in reality neither would make a significant difference.)

Many Thanks

EDIT

Any links, or references might be useful for the purposes of this discussion. Thanks :-)


I'd say that it's extremely unlikely that it makes any real-world difference. In theory, yes, there's one fewer check required (because div#foo really does need to be a div to match the selector, according to the spec). But the odds of it making any real difference in a real-world browser app? Near zero.

That said, I always cringe when I see things like div#foo in HTML applications. HTML has only one ID-type attribute (id), so there's no need for the further qualification. You make the CSS selector engine (either the browser's or jQuery's) work harder to figure out what you mean, you make the selector fragile (if the div becomes a footer, for instance), etc., and of course you do leave yourself open to a stoopid selector implementation that fails to recognize that it can look something up by ID and then check to see if it's a div and so goes looking through all the divs. (Does such an implementation exist? Possibly, you never know.) Barring some edge cases, it always makes me think someone doesn't quite know what they're doing.

So for me, speed isn't the main argument. Pointlessness is. ;-)


yes this is faster because of parsing speed and because browser must not check if element is also a <div>. (for a few rules speed difference is not perceivable by the user)


According to this Mozilla article, it does make a difference, although a minute one. (Note that while that article discusses styling XUL user interfaces, the Gecko layout engine is used both for rendering Firefox's user interface and the Web pages it loads.)

The ID is meant to apply to a single element in the DOM anyway, so the performance hit incurred by attempting to match the tag name is completely unnecessary, whether significant or not. Not to mention it would waste a few bytes in your stylesheet as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜