如果该函数被多次调用,那么在函数中缓存选择器会更高效吗? [英] Is it more performant to cache a selector in a function if that function's called multiple times?
问题描述
好的,我想我知道答案,希望确认一下。所以我有一个只使用过一次的选择器,但是它被用在一个多次调用的函数中。从性能的角度来看,因为每次调用函数时都会重新搜索该选择器,所以缓存选择器可能(尽管稍微)更好吗?
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()
})
推荐答案
显然, jQuery()
调用以比jQuery对象的变量引用更少的总时间完成。上次运行记录
Evidently, jQuery()
call completes in less total time than variable reference to jQuery object. Last run logged
- jQuery():16.580ms
- 缓存jQuery()对象: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>
这篇关于如果该函数被多次调用,那么在函数中缓存选择器会更高效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!