弱引用的其他用途? [英] Other uses of weak references?

查看:78
本文介绍了弱引用的其他用途?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,弱引用是记住可能大量数据的很好的候选者,并且维基百科有关弱引用的文章仅列出跟踪应用程序中正在引用的当前变量",并且语句弱引用的另一种用法是编写缓存".

I know that weak references are a good candidate for memoizing potentially large sets of data, and Wikipedia's article on weak references only lists "keeping track of the current variables being referenced in the application" and the statement "Another use of weak references is in writing a cache".

还有什么其他情况(不仅仅是缓存结果"更具体),其中使用弱引用是一个好主意 TM ?

What are some other situations (more specific than just "caching results") where the use of weak references is A Good IdeaTM?

推荐答案

弱引用的主要正确用法是识别其重要性源自强引用的存在.两种最常见的情况是:

The primary correct use for weak references is to identify things whose importance derives from the existence of strong references to them. The two most common scenarios are either:

  • 一个对象持有对某事物的引用,不是因为它关心"所讨论的对象,而是因为其他关心该对象的实体可能希望它对该对象执行某些操作.如果不久之后没有人在乎该对象,则没有理由其他实体继续代表所有关心它的实体"来操纵它.

  • An object holds a reference to something not because it "cares" about the object in question, but rather because other entities which do care about the object might want it to do something with it. If after awhile nobody cares about the object anymore, there's no reason why other entities should continue to manipulate it on behalf of "all the entities that care about it".

持有多个对同一不可变对象的引用的内存开销可能比持有对许多相同对象的引用的内存开销低得多,比较同一对象的引用可能比比较同一对象的引用快得多. .创建不可变对象,将其废弃,收集该对象以及创建相同对象的内存成本与创建对象并随后返回第二个引用的成本基本相同.返回对必须仍然保留的现有对象的引用是一个大赢家;返回对符合收集条件但尚未收集的对象的引用可能会或可能不会是一次胜利(通常是一次小小的胜利,但在世代GC中,有时会稍微损害性能);在许多情况下,后一种好处不足以证明使一个对象活着的时间比其他必要时间更长.

The memory cost of holding many references to the same immutable object may be much lower than the memory cost of holding references to many identical objects, and comparing references to the same object may be be much faster than comparing identical objects. The memory cost of creating an immutable object, abandoning it, having it get collected, and creating an identical object is essentially the same as the cost of creating an object and later returning a second reference to it. Returning a reference to an existing object which would have to be retained anyway is a big win; returning a reference to an object which was eligible for collection but hadn't been collected yet may or may not be a win (it's usually a slight win, but in a generational GC it can sometimes hurt performance slightly); in many cases, the latter benefits would not be sufficient to justify keeping an object alive longer than would otherwise be necessary.

这篇关于弱引用的其他用途?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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