Is it more performant to cache a selector in a function if that function's called multiple times?

前端 未结 2 1544
甜味超标
甜味超标 2021-01-06 09:00

Ok I think I know the answer to this, looking to confirm. So I have a selector that\'s only used once, but it\'s used inside a function that\'s called several times. From a

相关标签:
2条回答
  • 2021-01-06 09:35

    Evidently, jQuery() call completes in less total time than variable reference to jQuery object. Last run logged

    • jQuery(): 16.580ms
    • cached jQuery() object: 22.885ms

    (function() {
    
      function testFunction() {
        $("#input").val()
      }
    
      console.time("jQuery()");
    
      for (let i = 0; i < 10000; i++) {
        testFunction()
      }
      
      console.timeEnd("jQuery()");
      
    })();
    
    (function() {
    
      let input = $("input");
    
      function testFunction() {
        input.val()
      }
    
      console.time("cached jQuery() object");
    
      for (let i = 0; i < 10000; i++) {
        testFunction()
      }
      
      console.timeEnd("cached jQuery() object");
      
    })();
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
    </script>
    <input>

    0 讨论(0)
  • 2021-01-06 09:49

    Yes you are right the second one is more efficient than the first one because

    In the first one to select the input filled first it going to find the input field then it select that input field,And this will happen each time of function call.

    But in second case the selector is select once when the page is loaded the it refers that selector through the variable and will not go to find that input field in each call.That why 2nd one is more efficiency.

            <input value='Value' id='input'><br>
            <span id='tt'>dssd</span><br>
            <span id='t1'></span><br>
            <span id='t2'></span>
    

    And Jquery:-

     function testFunction1() {
            var t=$("#input").val()
            $("#tt").html(t);
        }
        console.time("jQuery() object");
        var t1=performance.now();
        for (var i = 0; i < 50000; i++) {
            testFunction1()
        }
        console.timeEnd("jQuery() object");
    
        var t2=performance.now();
        t2=t2-t1;
        $("#t1").html('Without selector variable:- '+t2);
        var input = $("input");
        function testFunction2() {
            var t=input.val();
            $("#tt").html(t);
        }
         t1=performance.now();
        console.time("cached jQuery() object");
        for (var i = 0; i < 50000; i++) {
            testFunction2()
        }
         t2=performance.now();
        console.timeEnd("cached jQuery() object");
        t2=t2-t1;
        $("#t2").html('With selector variable:- '+t2);
    

    Just Check here:-click here

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