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

查看:151
本文介绍了为什么要缓存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','凉');
$('#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天全站免登陆