jQuery optimization selector

后端 未结 4 1560
难免孤独
难免孤独 2021-02-06 08:47

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.

4条回答
  •  无人及你
    2021-02-06 09:39

    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 ). Compare to this example:

    $('#myId .someElement')
    

    This would have to scan every sub-element of #myId.


    Edit: As FelixKing pointed out, your first example $('#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).

提交回复
热议问题