0

I'm creating a game in C# and XNA 4.0. It consists of multiple levels with a player character, enemies, things to collect, etc. The levels are created using a Level class similar to the following.

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());
}

In order to add the enemies and such, I'm also using classes such as Enemy and Item. They are created in the same way.

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

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

The game is currently working as it should, but by the time it's finished I'll be using hundreds of new object instances. Can using too many new instances cause memory issues in C#? If so, how would anyone recommend reorganising the level/enemy/item creation to cut down on memory usage?

  • Depends on how much RAM you have. But why exactly are you creating all the levels and what they contain at once instead of when you need them? And too many GameObjects/DrawableGameObjects activated at the same time (about 10 000+) can cause severe lag issues, if the Update/Draw method did not finish going through them all before the next tick. – Pierre-Luc Pineault May 10 '15 at 22:28
  • I think you will hit an issue with slow memory retrieval before memory usage becomes a problem. Consider using a Dictionary collection instead of a List if your game code will be reading the collections often. – failedprogramming May 10 '15 at 22:31
  • 2
    Beware of premature optimization. See http://stackoverflow.com/a/1903245/76337. – John Saunders May 10 '15 at 23:10
  • 1
    **Optimisation tip**: You arguably don't need to store all the `Level`s in memory. Merely load the level on demand. –  May 11 '15 at 04:33

2 Answers2

2

The overhead of a single instance is only about 20 bytes (a reference and internal data in the object). Having hundreds of objects in memory would only cause a few kilobyte of overhead, so just creating those instances is not going to be a problem in itself.

So, if having those instances in memory will cause any problem depends entirely on how much data you have in each object.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

you can use the process.workingset to get process memory usage. https://msdn.microsoft.com/en-us/library/system.diagnostics.process.workingset.aspx

Ravi
  • 1
  • 3
  • That arguably does not answer the question. It reads more as a mechanism to gather metrics –  May 11 '15 at 04:31