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

前端 未结 2 1557
甜味超标
甜味超标 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");
      
    })();
    
    

提交回复
热议问题