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

前端 未结 2 1543
甜味超标
甜味超标 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: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.

            
    dssd

    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

提交回复
热议问题