WeakReference 是否有冗余属性?
.NET 中的 WeakReference 实现具有 IsAlive 属性。
1) 使用 IsAlive
属性或测试 Target
属性是否不为 null 之间是否存在性能/行为差异?
2) IsAlive
是一个多余的属性吗?
谢谢。
WeakReference implementation in .NET has an IsAlive Property.
1) Are there any performance/behavior differences between using the IsAlive
property or testing whether the Target
property is not null?
2) IsAlive
is a redundant property?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
1) 不。在内部,IsAlive 执行的逻辑与检查目标几乎完全相同,并查看它是否为空。
2) 某种程度上,因为检查
ref.Target != null
是否与ref.IsAlive
相当。然而,IsAlive
更具表现力,并且在维护代码时可能更容易理解。1) No. Internally, IsAlive is doing almost exactly the same logic as checking target, and seeing if it's null.
2) Somewhat, since checking whether
ref.Target != null
is pretty much equivelent toref.IsAlive
. However,IsAlive
is more expressive, and potentially easier to understand when maintaining the code.查看源代码,它们之间的行为没有区别。
obj.IsAlive
比obj.Target != null
更方便、更易读。Looking at the source code, there is no difference in behavior between them.
obj.IsAlive
is simply more convenient and readable thenobj.Target != null
.不难想象一个并发垃圾收集系统,其中即使是暂时持有对对象的引用,也很有可能导致该对象在下一次 GC 中幸存下来(在 .Net 下,这样做的可能性相对较小) )。在这样的系统下,使用对象的 Target 属性来确定它是否已死亡可能会产生恼人的副作用,即使对象的存活时间超过必要的时间。使用 IsAlive 属性可以避免这种风险。
请注意,IsAlive 只能可靠地用于确定对象是否已死亡。如果它报告某个对象还活着,则它可能会也可能不会获取其目标。
It is not hard to imagine a concurrent garbage-collection system in which holding a reference to an object even momentarily would have a substantial likelihood of causing that object to survive the next GC (under .Net, it has a relatively small likelihood of doing so). Under such a system, using an object's Target property to determine if it was dead could have the annoying side-effect of keeping the object alive longer than necessary. Using the IsAlive property would avoid that risk.
Note that IsAlive can only be used reliably to determine if an object is dead. If it reports that an object is alive, it may or may not be possible to acquire its target.