jQuery Selectors, efficiency

前端 未结 6 703
既然无缘
既然无缘 2020-12-08 23:16

I have been reading more lately about the efficiency of the different selector engines. I know that jQuery uses the Sizzle engine and this blog post about some jQuery stuff

相关标签:
6条回答
  • 2020-12-08 23:43

    JsPerf: http://jsperf.com/jquery-id-vs-tagname-id

    The first one is going to be faster because it only has to check the id. The second one runs the same check AND has to make sure the tagname is correct. div#id won't give you the element with id id unless it is a div

    0 讨论(0)
  • Rather than speculating, let's measure it!

    Here's a test case with this page loaded, then matching a random element with both methods.

    Make sure you scroll right down to the bottom.

    http://jsperf.com/which-jquery-sizzle-selector-is-faster#runner

    As you might expect, a plain id is faster than a tag qualified one (reduction to getElementByID). This is the same when using classes.

    Selecting by ID is massively faster than selecting by class, mainly as IDs are guaranteed to be unique.

    0 讨论(0)
  • 2020-12-08 23:53

    jQuery and Sizzle optimize the #id selector [source] to document.getElementById(id). I think they aren't able to optimize it like this with the tag#id.

    The first is faster.

    BTW specifying the tag name for an #id selector is over-specifying, as there can be only one tag with a given id on the document. Over-specifying is slower even in CSS.

    0 讨论(0)
  • 2020-12-08 23:56

    If you are using jQuery, you can assume a browser with getElementById. $('#someId') can be converted to document.getElementById('someId'). $('div#someId') won't be, so it will be faster to lose the tag name.

    jsPerf demonstrating this. The difference is enormous.

    0 讨论(0)
  • 2020-12-08 23:57

    You can see from the source code here: http://code.jquery.com/jquery-1.6.2.js in the function init.

    The fastest selector is $('') which just returns an empty jQuery object immediately.

    $('body') is next, which jQuery converts to document.body

    The next is $('#id') which uses document.getElementById('id').

    Any other selector such as $('div#id') will just become a call to $(document).find('div#id'). find() is very complex compared to any of those other solutions and uses Sizzle JS to select the div.

    0 讨论(0)
  • 2020-12-09 00:01
    var div = $('#someId'); //should be faster
    

    jQuery will use getElementById() for the above selector

    var div = $('div#someId'); //would probably preform slower due to finding all the divs first
    

    jQuery will use getElementsByTagName(), then iterate though the array of elements for the above selector

    You should also remember, tag names should definately be used with class selectors (whenever possible)

    var div = $('div.myclass') //faster than the statement below
    

    versus

    var div = $('.myclass') //slower
    
    0 讨论(0)
提交回复
热议问题