为什么jQuery的.data()函数能更好地防止内存泄漏? [英] Why .data() function of jQuery is better to prevent memory leaks?

查看:86
本文介绍了为什么jQuery的.data()函数能更好地防止内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于jQuery实用程序函数jQuery.data(),在线文档说:

Regarding to jQuery utility function jQuery.data() the online documentation says:


jQuery.data()方法允许我们
以任意方式将任何类型的数据附加到DOM
元素,从
循环引用开始,因此从
内存泄漏安全。

"The jQuery.data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks. "

为何使用:

document.body.foo = 52; 

会导致内存泄漏 - 或者在什么条件下 - 以便我应该使用

can result a memory leak -or in what conditions- so that I should use

jQuery.data(document.body, 'foo', 52);

在任何情况下,我是否总是更喜欢.data()而不是使用expandos?

Should I ALWAYS prefer .data() instead of using expandos in any case?

(如果你能提供一个比较差异的例子,我将不胜感激)

(I would appreciate if you can provide an example to compare the differences)

谢谢,

burak ozdogan

burak ozdogan

推荐答案

更好的原因是因为你在报价中所说的内容:不受循环引用的影响。

假设您有变量 nodeOne nodeTwo ,它引用节点。

Say you have variables nodeOne and nodeTwo, which reference nodes.

然后说你把它放在一个函数中(你没有存储它的引用):

Say you then put this in a function (whose reference you don't store):

jQuery.data(nodeOne, 'item', nodeTwo);
jQuery.data(nodetwo, 'item', nodeOne);

函数运行后,有一个循环引用:nodeOne有一个对nodeTwo的引用,反之亦然。

After the function runs, there's a circular reference: nodeOne has a ref to nodeTwo, and vice versa.

通过使用jQuery.data,该循环引用不会阻止这两个变量被垃圾收集。

By using jQuery.data, that circular reference won't prevent those two variables from being garbage collected.

但是,如果你要做同样的事情,但没有使用jQuery.data, nodeOne nodeTwo 变量不会被垃圾收集,即使不再需要变量。

However, if you were to do the same thing but without using jQuery.data, the nodeOne and nodeTwo variables would not be garbage collected, even if the variables are no longer needed.

-


我是否总是更喜欢.data()而不是
在任何情况下使用expandos?

除非您正在进行大量数据设置并且需要任何额外的性能下降(并且您可以通过使用性能分析来判断)并确保您不会创建循环引用(或至少一个重要的数字,然后是的,你也可以只使用jQuery.data。

Unless you're doing large amounts of data setting and need any extra drops of performance (and you could tell by using profiling) and are sure you won't create circular references (or at least a number that would matter), then yes, you may as well only use jQuery.data.

这篇关于为什么jQuery的.data()函数能更好地防止内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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