Element + ID vs only ID in jquery?

前端 未结 3 455
情歌与酒
情歌与酒 2021-01-17 07:14

div#some_id will scan through all the divs throughout the DOM.

#some_id will pick up the ID directly from the DOM.

So which is fast

相关标签:
3条回答
  • 2021-01-17 07:27

    See Optimize Selectors:

    Beginning your selector with an ID is always best.

    and

    ID-only selections are handled using document.getElementById(), which is extremely fast because it is native to the browser.

    So the answer is: $('#some_id') should be faster.

    0 讨论(0)
  • 2021-01-17 07:28

    As ID are supposed to be unique in DOM, so div#some_id will be doing unnecessary scan on all DOM elements and #some_id will do a direct scan on it.

    You can also see the result here: div-some-id-vs-some-id

    0 讨论(0)
  • 2021-01-17 07:34

    I ran a simple test here in the console. It seems just using #id is faster as @Ulli said. Here is the test code:

    var perf = performance;
    
    var a = perf.now(); $("#custom-header"); console.log(perf.now() - a);
    VM795:2 0.03399999695830047
    undefined
    var a = perf.now(); $("#custom-header"); console.log(perf.now() - a);
    VM796:2 0.0329999893438071
    undefined
    var a = perf.now(); $("#custom-header"); console.log(perf.now() - a);
    VM797:2 0.0329999893438071
    undefined
    var a = perf.now(); $("#custom-header"); console.log(perf.now() - a);
    VM798:2 0.03500000457279384
    undefined
    var a = perf.now(); $("div#custom-header"); console.log(perf.now() - a);
    VM799:2 0.07000000914558768
    undefined
    var a = perf.now(); $("div#custom-header"); console.log(perf.now() - a);
    VM800:2 0.06600000779144466
    undefined
    var a = perf.now(); $("div#custom-header"); console.log(perf.now() - a);
    VM801:2 0.0680000230204314
    undefined
    var a = perf.now(); $("div#custom-header"); console.log(perf.now() - a);
    VM802:2 0.06799999391660094
    undefined
    var a = perf.now(); $("div#custom-header"); console.log(perf.now() - a);
    VM803:2 0.06799999391660094
    undefined
    
    0 讨论(0)
提交回复
热议问题