I was wondering the other day when typing you selectors in jQuery would it make a difference in performance if you specify your selectors very specific or very loosely.
The second one will be faster, since it knows exactly what to look for at each step.
In this example:
$('table#myId > tbody > tr > td > div.someElement');
If there were no tbody, or no tr, or no td (etc), it could shortcut out of the search straight away. Also, every subsequent step will narrow down the search (eg: not searching inside the This would have to scan every sub-element of Edit: As FelixKing pointed out, your first example ). Compare to this example:
$('#myId .someElement')
#myId
.
$('#myId .someElement')
is actually faster. Only marginally, but still, faster, so I thought I should respond. Using the child selector (>
), as opposed to the descendant selector (a space) is the fastest traversal method, since the possible set of elements is much less. However, modern browsers have highly optimised built-in methods which jQuery can sometimes make use of, actually reducing the execution time. So, as seen in this particular case, the 'worse' one is actually better, since the browsers are better optimised for executing that particular query. In general however, the original point still stands, particularly if you're using something which couldn't possibly be optimised by browsers (custom selectors, for example).