弱参考收益 [英] Weak reference benefits

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

问题描述

谁能解释一下 C# 中不同类型引用的主要好处?

Can someone explain the main benefits of different types of references in C#?

  • 弱引用
  • 软引用
  • 幻影参考
  • 强有力的参考.

我们有一个消耗大量内存的应用程序,我们正在尝试确定这是否是一个需要关注的领域.

We have an application that is consuming a lot of memory and we are trying to determine if this is an area to focus on.

推荐答案

我相信软引用和幻像引用来自 Java.长弱引用(将 true 传递给 C# 的 WeakReference 构造函数)可能被认为类似于 Java 的 PhantomReference.如果在 C# 中有一个类似于 SoftReference 的,我不知道它是什么.

Soft and phantom references come from Java, I believe. A long weak reference (pass true to C#'s WeakReference constructor) might be considered similar to Java's PhantomReference. If there is an analog to SoftReference in C#, I don't know what it is.

弱引用不会延长对象的生命周期,因此一旦所有强引用都超出范围,就可以对其进行垃圾回收.它们对于保持初始化成本高的大对象很有用,但如果它们没有被积极使用,则应该可用于垃圾收集.

Weak references do not extend the lifespan of an object, thus allowing it to be garbage collected once all strong references have gone out of scope. They can be useful for holding on to large objects that are expensive to initialize, but should be available for garbage collection if they are not actively in use.

这是否有助于减少应用程序的内存消耗将完全取决于应用程序的具体情况.例如,如果您有适量的缓存对象,这些对象将来可能会或可能不会被重用,那么弱引用可以帮助改善缓存的内存消耗.但是,如果应用程序处理大量小对象,弱引用会使问题变得更糟,因为引用对象会占用同样多或更多的内存.

Whether or not this will be useful in reducing the memory consumption of your application will depend completely on the specifics of the application. For example, if you have a moderate number of cached objects hanging around that may or may not be reused in the future, weak references could help improve the memory consumption of the caches. However, if the app is working with a very large number of small objects, weak references will make the problem worse since the reference objects will take up as much or more memory.

这篇关于弱参考收益的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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