javascript - 用变量替换 $(this) 是否会产生任何性能差异

标签 javascript jquery

<分区>

我有一个看起来像这样的循环:

$('#SomeSelectorID').find('.SomeElementsByClassName').each(function () {

    $(this).some code here;
    $(this).some other code there;
    $(this).some other code here and there;
});

如果我在循环的顶部写入 var TheThis = $(this); 然后将 $(this) 替换为 TheThis这真的是性能优化吗?

最佳答案

这是一个明确的性能优化。一个你可能不会注意到,但没有理由不去做。

您示例中的代码意味着 DOM 将被询问 3 次以查找 $(this) 元素,然后对其执行操作。将它缓存在一个变量中意味着它只会发生一次。

如果您真的想看到差异,请尝试将您的原件与下面的 JSPerf 进行比较测试。

$('#SomeSelectorID').find('.SomeElementsByClassName').each(function () {
    var $this = $(this);
    $this.some code here;
    $this.some other code there;
    $this.some other code here and there;
});

关于javascript - 用变量替换 $(this) 是否会产生任何性能差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14591905/

相关文章:

javascript - Accordion with jQuery (not jQueryUI) - 有一种 "DRY"方法可以做到这一点..只是不知道如何

c# - 通过 JInt 检查有效的 jQuery 代码时出现 "document is not defined"错误?

javascript - 将焦点设置到下一个输入

javascript - 具有单个或多个数据源的两个垫分页器无法正常工作

javascript - 如何在 Vue JS 中获取 main.js 文件中的全局数据?

javascript - 从 Servlet 重定向 GWT 应用程序

javascript - 添加 Bokeh curdoc 的自定义脚本

javascript - jQuery val() 用于字符串数组

PHP 等待创建 PDF,然后通过邮件发送?

javascript - 我可以取消附加到父 div 的子 div 的所有 jquery 事件吗?