user4721723
user4721723

Reputation:

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

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?

Upvotes: 0

Views: 1560

Answers (2)

Guffa
Guffa

Reputation: 700242

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.

Upvotes: 2

Ravi
Ravi

Reputation: 1

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

Upvotes: 0

Related Questions