jQuery select by class VS select by attribute

前端 未结 2 2074
生来不讨喜
生来不讨喜 2020-11-29 09:06

I want just to ask for an opinion of perfomance: Is it faster selecting elements by class name or by attribute name with jquery? Example I have 100 DIVs element in this form

相关标签:
2条回答
  • 2020-11-29 09:36

    Here is are the results of a test I just ran for myself. This div was on a DOM with 1562 elements.

    <div class="banana" data-banana="1"></div>

    Tests

        function test(iterations) {
    
        console.time('query-by-data');
        for(var i=iterations;i;i--) {
            $('[data-banana]');
        }
        console.timeEnd('query-by-data');
    
        console.time('query-by-class');
        for(var i=iterations;i;i--) {
            $('.banana');
        }
        console.timeEnd('query-by-class');
    
    }
    

    results

     iterations: 1000
     query-by-data: 120.000ms
     query-by-class: 10.000ms
    
     iterations: 10000
     query-by-data: 1030.000ms
     query-by-class: 56.000ms
    
     iterations: 50000
     query-by-data: 5151.000ms
     query-by-class: 235.000ms
    
    0 讨论(0)
  • 2020-11-29 09:55

    this is a great post for exactly what you are looking for.

    JQUERY SELECTOR PERFORMANCE TESTING

    I've also found a great article that may help you on this topic:

    • some jquery selectors performance tests

    let me know if this answer really helped you, thanks.

    update: I've managed to make a sample to match your posted case, here are the results for a total set of 203 divs:

    1- by using tag name having certine class name $("div.normal_box") ==> 884 ms

    2- by using attribute value $("div[normal_box=1]") ==> 4553 ms

    Update 2: I tried even further more than your question, and made it to test a few selectors, here is the new link for this updated test: http://jsfiddle.net/8Knxk/4/

    3- by using tag name $("div") ==> 666 ms

    4- by using just the class name $(".normal_box") ==> 762 ms

    I think it's now more clear for you :)

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