The 2014 book Writing High-Performance .NET Code contains tips on coding effective C#, above and beyond the Zen of Performance. It made me consider the usage of value types,
struct instead of
struct for small structures, we achieve less memory usage, better memory locality and fewer garbage collections. Arrays of structs have good memory locality, utilising the CPU caches and improving performance due to more cache hits.
As all other value types in C#, your structs should be immutable. Set your fields and properties
readonlyand create custom constructors. As structs can always be constructed using the default constructor, the default values for all fields and properties must make sense in your context.
IEquatable<T>. The default
Equalsimplementation uses reflection and boxing and should be avoided. Also override
bool Equals(object obj)and
Keep them small, Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries suggests under 16 bytes. Since value types are copied unless passed by reference (
ref), performance will degrade if the
structbecomes too big. C# classes have a pointer size of 4 bytes, 8 bytes for x64 applications, and an overhead of 8 bytes. Structs are just as big as the data they contain. Below are a table of the sizes of the built in value types:
- The data fits together logically as a single entity
- It will have a small size
- It will be immutable
- It will not be used often in a way that will cause boxing
For all else, use