Skip to content

Remove right-hand side specificity recommendation #696

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
dare05 opened this issue Jan 21, 2016 · 1 comment
Closed

Remove right-hand side specificity recommendation #696

dare05 opened this issue Jan 21, 2016 · 1 comment

Comments

@dare05
Copy link

dare05 commented Jan 21, 2016

In http://learn.jquery.com/performance/optimize-selectors/ you say:

"Be specific on the right-hand side of your selector, and less specific on the left."

I've opened a thread on SO: http://stackoverflow.com/questions/34923710/selectors-be-specific-on-right-hand-side

Two people so far have done benchmarks and the version where the right-hand side is more specific is always performing worse. Basically, in modern browsers supporting queryselectorall, as far as I'm aware, the Sizzle engine is not used for processing the selector. So basically, as far as I'm aware, in modern browsers, it's about how many operation there are to evaluate the result.

In $( ".data .gonzalez" ), there are 2 operations (1 for looking up CSS class results, 1 for tag results), while in $( ".data td.gonzalez" ) there are 3 operations (2 for looking up CSS class results, 1 for tag results) which is why I suspect the second version is slower in most browsers.

Correct me if I'm wrong.

@Krinkle
Copy link
Member

Krinkle commented Mar 26, 2023

There are index optimisations in browsers for class-based selection, so a simpler selector overall will generally perform faster. However, to the best of my knowledge, it remains accurate that browsers resolve selectors from right to left, and that if you need specificity, it'll be faster to filter this out on the right-hand side first rather than later where it will have kept more results filtering up the DOM tree.

To observe these differences, the DOM needs to be quite large, and the alternative interpretations need to actually exist. If an example page contains only the elements you want to select and nothing else, than the other possibilities are not explored by the selector engine and thus won't slow you down.

Put another way, if you page contains 1 <div>, then the quickest way to select it is probably div. If your page contains 1000 div elements with different nesting levels and you're looking for two of them, then a selector like body div div.quux[x=y] will likely be faster than .foo[x=y] div div.

@Krinkle Krinkle closed this as completed Mar 26, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

2 participants