Updated
Let's assume we have a Plane
type with 4 doubles on 64bit system, and that we have 1 million Plane
s.
- If
SPlane
is a struct, then it would occupy 4*8 = 32 bytes
- If
CPlane
is a class, then it will occupy 4*8 bytes (fields) + 16 bytes (header) = 48 bytes. And don't forget about the 8 bytes for each reference pointing to each instance.
Let's consider the pros and cons of using a struct, instead of a class.
Pros
- GC Performance - there are less references to keep track of. The GC will treat an array of
SPlane
an one object. An array of CPlane
would have to be treated as 1 million + 1 objects.
- Memory space - an array of
SPlane
will occupy 32 million bytes in memory. An array of CPlane
will occupy 8 million bytes (array of contiguous references) + 48 million bytes (individual instances). Thats 32 million bytes vs 56 million bytes.
Cons
- Performance degradation due to copying
- "resizing"/"expanding" an array of struct planes would copy 32 million bytes, whereas if we were using classes, it would copy the references only (8 million bytes)
- likewise, things like passing a
SPlane
as an argument to a method, returning an SPlace
or assigning a variable to another variable, will copy 32 bytes, whereas passing CPlane
will copy just the reference.
- Usual caveats of using value types.
- no inheritance (doesn't seem to matter to you anyway)
- acidental boxing (implicit casting to object or interface, calling
GetType
or non-overriden ToString
). This one can be mitigated by being careful.
- no canonical form (no explicit parameterless constructor - you can't restrain the default value of a value type field). E.g., unassigned fields and arrays would, by default, be filled with persons of 0 height - considering
struct Person {int height;}
.
- no circular dependencies. A struct
Person
cannot contain fields of type Person
, as that would lead to an infinite memory layout.
Since we don't know your exact use cases, you'll have to make the decision.
Like Matthew Watson suggested, you should measure the performance of both approaches and compare.