How does memory use work in C# when adding the same object to different lists?

I am developing a game where 2 players each have many objects from a class called UnitObject, each of which can be on a different Army. Right now, the player class has a List of UnitObjects and at the same time, each Army has its own List for storing units that belong to it. I am new to c# and I am wondering if, when having hundreds of units, it would be better to have the player have a Dictionary<int, UnitObject> with the int being the id of said unit, so that other classes can have just a List of integers for reference. Do the UnitObjects in the Army duplicate the memory use of the ones in the Player or is it just a reference? My code could be (very) simplified to:

UnitObject unit =  new UnitObject();
army.units.Add(unit)
player.units.Add(unit)

This is an over simplification, my classes have other classes they belong to and is not as simple as to make the player have a list of armies or so. I am just wondering if by doing this, i am using double memory for each object.

Upvotes: 0

Views: 599

Answers (1)

Nicholas Carey
Nicholas Carey

Reputation: 74277

UnitObject is a reference type, unlike s struct or [most] primitive objects such as int, which are value types.

Reference objects are allocated independently, either on the the stack or the heap (depending). They are passed by reference: when you add an instance of a reference type (such as an instance of your UnitObject) to a collection, what it added is a reference to the actual object itself. A reference is a single processor word (32- or 64-bit, depending on processor architecture). It's not a pointer, more like a pointer to a pointer, to allow the allocated object to be moved by the garbage collector if need be.

You when you add an instance of your UnitObject to two different collections, they both point to the same instance of UnitType.

And if you pass a reference type to a method, it is passed by reference: any changes made to the passed object by the called function persist once control returns to the caller.

Value types, are passed by value, näturlich, so adding something like an int to a collection means the collection receives a copy of the value. Ditto for passing value types to method: the method receive a copy of the value.

Upvotes: 1

Related Questions