gpt4 book ai didi

jQuery "$(this)": is repeated use efficient?

转载 作者:行者123 更新时间:2023-12-01 00:09:49 26 4
gpt4 key购买 nike

重复使用 $(this) 是否有效,还是将其保存到变量中更好?我已经看到它在很多 jQuery 代码中重复使用,但由于它是对构造函数的调用,我认为它应该不必要地慢,我错了吗?

最佳答案

只是为了好玩 - 测量。要查看差异,您需要调用 $(this) 数万次(取决于 CPU)。

100,000 次调用的差异大约为 10070 毫秒,其中 $(this) 为慢一点。

var testCount = 100000;

$('div').each(function(){
var self = $(this);

// Measurement using $(this) selector
var t1 = new Date();
for (var i = 1; i <= testCount; i++){
var nil = $(this).attr('id');
}
console.log('T1', (new Date()) - t1);

// Measurement using saved declaration
var t2 = new Date();
for (var i = 1; i <= testCount; i++){
var nil = self.attr('id');
}
console.log('T2', (new Date()) - t2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
</div>

就我个人而言,我仍然使用保存的声明 var self = $(this) 因为编写更优化的代码始终是一个好习惯,而且还因为不同的上下文可能导致一些混淆(如所述在其他答案中)。

关于jQuery "$(this)": is repeated use efficient?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39038650/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com