Jquery element+class selector performance

后端 未结 4 935
萌比男神i
萌比男神i 2020-12-12 18:09

I was hoping $(\'#childDiv2 .txtClass\') or $(\'#childDiv2 input.txtClass\') perform better when selecting

相关标签:
4条回答
  • 2020-12-12 18:46

    Modern browsers expose a very efficient getElementsByClassName() method that returns the elements having a given class. That's why a single class selector is faster in your case.

    To elaborate on your examples:

    $(".txtClass")                  =>  getElementsByClassName()
    
    $("#childDiv2 .txtClass")       =>  getElementById(),
                                        then getElementsByClassName()
    
    $("#childDiv2 > .txtClass")     =>  getElementById(),
                                        then iterate over children and check class
    
    $("input.txtClass")             =>  getElementsByTagName(),
                                        then iterate over results and check class
    
    $("#childDiv2 input.txtClass")  =>  getElementById(),
                                        then getElementsByTagName(),
                                        then iterate over results and check class
    

    As you can see, it's quite logical for the first form to be the fastest on modern browsers.

    0 讨论(0)
  • 2020-12-12 18:48
    var obj = document.getElementById("childDiv");
    xxx = obj.getElementsByClassName("txtClass");
    

    is 30x faster.

    http://jsperf.com/selectors-perf/6

    0 讨论(0)
  • 2020-12-12 18:53

    CSS Selectors are parsed from right to left. So your example

    $('#childDiv2 .txtClass')
    

    will take two actions to complete. First find all elements with class txtClass. Then check each element for being a child of the element with the id childDiv2.

    $('.txtClass')
    

    This selector will just take one action. Find all elements with class txtClass

    Have a look at this article on css-tricks.com

    0 讨论(0)
  • 2020-12-12 19:06

    Looks like it also depends on the density of the elements with the class among the elements of the type.

    I ran the tests with Google Chrome Version 30.0.1599.69 using JQuery 1.10.1. Feel free to try it on another browser and/or using another JQuery version.

    I tried to run the following tests:

    1. Sparse (10% of the div's have the class) link to the test on jsbin

    2. Dense (90% of the div's have the class) link to the test on jsbin

    Looks like in the Dense case div.class wins, but in the Sparse case .class wins.

    0 讨论(0)
提交回复
热议问题