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 performance perspective, since that selector is re-searched-for each time the function is called, it's probably (albeit marginally) better to cache the selector?
In other words, the below...
function testFunction() {
alert($("#input").val())
}
$("#a").click(function() {
testFunction()
})
$("#b").click(function() {
testFunction()
})
$("#c").click(function() {
testFunction()
})
...is not as performant as the below
input = $("#input")
function testFunction() {
alert(input.val())
}
$("#a").click(function() {
testFunction()
})
$("#b").click(function() {
testFunction()
})
$("#c").click(function() {
testFunction()
})
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.
And Jquery:-
Just Check here:-click here
Evidently,
jQuery()
call completes in less total time than variable reference to jQuery object. Last run logged