在 C# 中使用太多新实例会导致内存问题吗?

Can you use too many new instances in C# to cause memory issues?

我正在用 C# 和 XNA 4.0 创建游戏。它由多个关卡组成,包括玩家角色、敌人、要收集的东西等。关卡是使用类似于以下的关卡 class 创建的。

List<Level> levels = new List<Level>(20); //This is a list to hold all of the levels (There are 20 levels in this example)

//This loop creates each level using a new instance of the class
for (int i = 0; i < levels.Capacity; i++)
{
    levels.Add(new Level());
}

为了添加敌人等,我还使用了 classes,例如 Enemy 和 Item。它们的创建方式相同。

List<Enemy> enemies = new List<Enemy>();
enemies.Add(new Enemy());

List<Item> items = new List<Item>();
items.Add(new Item());

游戏目前运行正常,但在完成时我将使用数百个新对象实例。使用太多新实例会导致 C# 中出现内存问题吗?如果是这样,有人会如何建议重新组织 level/enemy/item 创建以减少内存使用量?

您可以使用 process.workingset 获取进程内存使用情况。 https://msdn.microsoft.com/en-us/library/system.diagnostics.process.workingset.aspx

单个实例的开销只有20字节左右(对象中的引用和内部数据)。在内存中拥有数百个对象只会导致几千字节的开销,因此仅创建这些实例本身不会成为问题。

因此,如果将这些实例放在内存中会导致任何问题,则完全取决于每个对象中有多少数据。