为什么要缓存 jQuery 对象? [英] Why cache jQuery objects?

查看:24
本文介绍了为什么要缓存 jQuery 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

那么我们为什么要缓存 jQuery 对象?

So why are we supposed to cache jQuery objects?

在以下场景中:

var foo = $('#bar');
foo.attr('style','cool');
foo.attr('width','123');

$('#bar').attr('style','cool');$('#bar').attr('width','123');

为什么第一个选项比第二个选项好这么多?

Why is the first option so much better than the second option?

如果是因为性能,它是如何减少使用的?

If it's because of performance, how does it reduce usage?

推荐答案

因为 jQuery 函数中包含大量代码,如果您使用相同的输入期望相同的输出多次执行它,则会产生不必要的开销.通过缓存结果,您可以存储对您正在查找的确切元素或元素集的引用,因此您不必再次搜索整个 DOM(即使搜索速度相当快).在许多情况下(带有少量代码的简单页面),您不会注意到有什么不同,但在您这样做的情况下,可能会产生很大的不同.

Because the jQuery function has a lot of code in it, which involves unnecessary overhead if you execute it more than once with the same inputs expecting the same outputs. By caching the result, you store a reference to the exact element or set of elements you're looking for so you don't have to search the entire DOM again (even if it's a fairly fast search). In many cases (simple pages with small amounts of code) you won't notice a difference, but in the cases where you do it can become a big difference.

您可以通过在 jsPerf 中测试您的示例来看到这一点.

You can see this in action by testing your example in jsPerf.

您也可以将其视为引入解释变量重构模式的示例,以提高可读性,尤其是比问题中的例子更复杂.

You can also think of it as an example of the Introduce Explaining Variable refactoring pattern for readability purposes, particularly with more complex examples than the one in the question.

这篇关于为什么要缓存 jQuery 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆