Is caching a selector in a function more efficient if the function is called several times?

Well, I think I know the answer to this question, wanting to confirm. Therefore, I have a selector that was used only once, but it was used inside a function that was called several times. In terms of performance, since this selector is re-scanned — every time a function is called, is it possible (albeit slightly) to cache the selector?

In other words, below ...

function testFunction() {
  alert($("#input").val())
}

$("#a").click(function() {
  testFunction()
})

$("#b").click(function() {
  testFunction()
})

$("#c").click(function() {
  testFunction()
})

... not as effective as below

input = $("#input")

function testFunction() {
  alert(input.val())
}

$("#a").click(function() {
  testFunction()
})

$("#b").click(function() {
  testFunction()
})

$("#c").click(function() {
  testFunction()
})
+4
source share
2 answers

, jQuery() , jQuery.

  • jQuery(): 16.580
  • jQuery(): 22.885

(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>
Hide result
+1

, , ,

, , , , .

, , . 2- .

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

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);

: -

0

Source: https://habr.com/ru/post/1678756/


All Articles