I’m making a 2D platformer game and to represent a level I’m using 2D array of tiles which are classes with fields for position, type and various flags. When I change the class key word in the tile class to struct, a loaded map consumes about 20% less memory.
I don’t know about rights and wrongs of this action, I just want to know why the difference in memory consumption.
Edit: numbers are 1038 MB with tiles as classes and 845 MB as structs (without most of game data).
An array of objects is actually an array of references, and the objects are stored on the heap.
That means that there is an overhead of 4 or 8 bytes (depending on x86 or x64) for the reference, and then there is an overhead of 8 or 16 bytes for each object on the heap.
In an array of structs, the struct values are stored directly in the array, so there is no extra overhead.
So, if your data is for example 48 bytes, the extra 12 bytes (in x86 mode) would be an overhead of 20% of the total memory used.
Note that there is also a difference in how they are used. If you move tiles around or send one as a parameter to a method, all the data will be copied if you use a struct, but only the reference is copied if you use a class. If you can keep the struct smaller than 16 bytes, the performance difference is small, but if it’s larger you may get faster code by using classes.