
In addition to classes that represent reference types, there are also structs that represent value types.
But how do the two different structures behave in terms of performance, and when can a class or a struct be used at all?
The key differences
- Structs are value types, allocated on the stack (or inline in containing types, based on compiler optimizations).
- Classes are reference types, allocated on the heap and managed by the garbage collector.
- Handling of structs is cheaper than handling classes, if we talk about allocations.
- Since structs are values, you copy those values (which costs time too!) instead of using an existing reference.
Performance comparison
1BenchmarkDotNet=v0.13.1, OS=Windows 10.0.19044.1415 (21H2)
2AMD Ryzen 9 5950X, 1 CPU, 32 logical and 16 physical cores
3.NET SDK=6.0.101
4 [Host] : .NET 6.0.1 (6.0.121.56705), X64 RyuJIT
5 DefaultJob : .NET 6.0.1 (6.0.121.56705), X64 RyuJIT
6
7
8| Method | Mean | Error | StdDev | Gen 0 | Allocated |
9|------------- |----------:|---------:|----------:|-------:|----------:|
10| SmallStruct | 39.16 ns | 0.069 ns | 0.061 ns | - | - |
11| MediumStruct | 39.30 ns | 0.254 ns | 0.238 ns | - | - |
12| SmallClass | 215.30 ns | 3.048 ns | 2.994 ns | 0.1433 | 2,400 B |
13| MediumClass | 487.58 ns | 9.713 ns | 15.959 ns | 0.2389 | 4,000 B |
Source: https://github.com/BenjaminAbt/SustainableCode
Benchmark Results
- 🔋 Both struct samples produce no allocations!
- 🚀 Struct has a better performance over all!
Remarks!
- The use of struct or class is part of the software architecture.
- Not in all scenarios struct makes sense or can be used (e.g. serialization)!
- The change from class to struct is a breaking change!
- It’s all a matter of perspective, whether these are small or large samples here - names are smoke and mirrors.

Comments