Speed difference between very similar jQuery expressions in IE
In IE, compare the speed of execution of an expression along the lines of
$('div.gallery div.product a");
to the very similar
$('div.gallery').find("div.product").find("a");
Sometimes the second variant runs faster, sometimes slow开发者_C百科er. Often the speed difference is a factor of 2 or more. What is going on?
The first variant will do the following:
- Find all anchor tags in the page
- Only leave the ones with ancestor
div.product
- Only leave the ones with ancestor
div.gallery
The second one
- Find elements with class
.gallery
and tagdiv
- Search for
div.product
in their descendants - Search for anchor tags in their descendants
So the first one will search for elements from right to left, while the second one will search them from left to right.
Which is faster depends on your site structure but the first one is the recommended way, because browsers match CSS selector the same way.
If you want to increase speed make sure that the rightmost selector is as specific as possible.
e.g.: in this case you can add a special class for your anchor tags like .gallery-link
and then your query will become a simple a.gallery-link
which in IE will invoke a getElementsByTagName
function for the anchor tags then they will be filtered by their class name. Notice that because you don't have to traverel up the DOM tree your query becomes significantly faster. The cost is a bit more complex markup. For costly queries it may worth it.
精彩评论