c# - 管理一个类的实例数

标签 c# out-of-memory

我有一个 B 类,我从中生成大量实例以加速优化问题中的一些搜索。这个数字变得如此之大以至于我经常产生 OutOfMemory-Exceptions。作为解决方法,我每 x 秒减少一次实例数,但我想做一些更明智的事情。为此,我想知道:

  1. 什么是管理“存活”实例(已创建但尚未被垃圾收集)数量的好方法

  2. 更具技术性:我如何估算我的实例必须使用(比如说)大约一半的 RAM?

最佳答案

首先,我会尽量减少每个对象的内存占用。由于您创建了大量对象,因此它们中的许多对象可能具有相似的属性,这使它们成为 flyweight pattern 的完美候选者。 .根据维基百科文章,一个经典的例子是文字处理:

A classic example usage of the flyweight pattern is the data structures for graphical representation of characters in a word processor. It might be desirable to have, for each character in a document, a glyph object containing its font outline, font metrics, and other formatting data, but this would amount to hundreds or thousands of bytes for each character. Instead, for every character there might be a reference to a flyweight glyph object shared by every instance of the same character in the document; only the position of each character (in the document and/or the page) would need to be stored internally.

作为第二步,我将估计单个对象的大小。我在此上下文中强调估计,因为获取实际大小是 not that easy in C# .然后可以使用此估计来设置最大数量的 N 对象,您可以安全地实例化这些对象而不会遇到 OutOfMemoryException

您可以通过在每次创建或销毁对象时更新对象计数器来跟踪有多少对象(大约)存活,从而利用此信息,例如

class Foo {

    private static NumberOfInstances = 0;

    public Foo() {
        NumberOfInstances++;
    }

    ~Foo() {
        NumberOfInstances--;
    }
}

如果线程安全是个问题,这个实现当然需要稍微改进一下。

编辑:正如 mike z 在他的评论中指出的那样,通过终结器实现它可能会导致严重的 performance problems在这种情况下。因此,最好实现 IDisposable 并在 Dispose 操作中执行递减。但是,这样做的缺点是可能会忘记处理对象。但是,我怀疑这在您的案例中会是一个严重的问题。

关于c# - 管理一个类的实例数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18174654/

相关文章:

c# - URL 路由在 2 个路由规则之间变得困惑

c# - 指示服务器请求失败的最佳实践方法?

.net - WinDbg内存分析

Maven gwt :compile forks to a different Xmx

swift - 减慢 didReceiveMemoryWarning() 中的进程

c# - 使用 SoundFonts 和 NAudio 播放 MIDI 文件

C# WPF 获取错误 - System.InvalidOperationException :

c# - 应该使用哪个 dataGridView 事件在编辑后立即更改文本框的内容?

c# - 加载图像时出现 WP8 内存不足错误

java.lang.OutOfMemoryError : unable to create new native thread 错误