It also depends on the browser. If the browser does not have a native selector implementation, or is missing getElementsByTagName
and getElementsByClassName
, etc. those will be "slower." getElementById
has always been native (as far back as I can remember), and should perform the best of all. It really depends on if the DOM engine has a cache or not, and what is cached during document parsing/rendering.
Remember, jQuery uses Sizzle under the hood, so this isn't really a question about jQuery, but Sizzle.
Sizzle attempts to use native DOM traversing methods, like matchSelector
, where possible. In some cases where a shiv is needed (like a :not(:has(span:eq(6))))
) non-native DOM traversal is required.
You should consider the complexity of the selector query, and from what part of the DOM tree the selector starts. Limiting your query is always faster than always starting from the root of the DOM: e.g. $('#main').find('.someClass')
or $('#main .someClass')
¹ as opposed to $('.someClass')
.
Perhaps this question is too open-ended.
¹ Per @nick-f, "Sizzle processes the selectors from right to left" so $('#main .someClass')
is not synonymous with $('#main').find('.someClass')
.