jquery, performance-wise what is faster getElementById or jquery selector?

后端 未结 8 1203
忘掉有多难
忘掉有多难 2020-12-04 15:45

What is better from performance wise document.getElementById(\'elementId\') or $(\'#elementId\') ? How can I calculate the speed by myself?

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 16:04

    I've just stumbled upon this post whilst wondering the same question... so decided to knock up a quick test script... run it, try it yourself, blew my mind!

    var now = Date.now();
    var diff = 0;
    console.log(now);
    
    for(var i=0; i < 1000000; i++)
    {
       if($(document.getElementById("test")).css('opacity') == '0.2')
           $(document.getElementById("test")).css('opacity', '1');
       else
          $(document.getElementById("test")).css('opacity', '0.2');
    }
    
    diff = Date.now() - now;
    console.log('With $(document.getElementById("test")).somejQueryCall(): ' + diff + ' milliseconds');
    
    ////////////////////////////////////////////////////////////////////////
    
    var now2 = Date.now();
    var diff2 = 0;
    console.log(now2);
    
    for(i=0; i < 1000000; i++)
    {
       if($("#test").css('opacity') == '0.2')
           $("#test").css('opacity', '1');
       else
          $("#test").css('opacity', '0.2');
    }
    
    diff2 = Date.now() - now2;
    
    console.log('With $("#test").somejQueryCall(): ' + diff2 + ' milliseconds');
    
    ////////////////////////////////////////////////////////////////////////
    
    var now3 = Date.now();
    var diff3 = 0;
    var elem = $("#test");
    console.log(now3);
    
    for(i=0; i < 1000000; i++)
    {
       if(elem.css('opacity') == '0.2')
           $(elem).css('opacity', '1');
       else
          $(elem).css('opacity', '0.2');
    }
    
    diff3 = Date.now() - now3;
    
    console.log('With $(elem).somejQueryCall(): ' + diff3 + ' milliseconds');
    

    After running this script, I got the following results:

    Run 1

    With $(document.getElementById("test")).somejQueryCall(): 552 milliseconds

    With $("#test").somejQueryCall(): 881 milliseconds

    With $(elem).somejQueryCall(): 1317 milliseconds

    Run 2

    With $(document.getElementById("test")).somejQueryCall(): 520 milliseconds

    With $("#test").somejQueryCall(): 855 milliseconds

    With $(elem).somejQueryCall(): 1289 milliseconds

    Run 3

    With $(document.getElementById("test")).somejQueryCall(): 565 milliseconds

    With $("#test").somejQueryCall(): 936 milliseconds

    With $(elem).somejQueryCall(): 1445 milliseconds

    I can't believe the difference!!! Just had to share this!

    Peace!

提交回复
热议问题