Exploring micro optimizations in c# Part 1 - using ref with structs
Follow the accompanying blog post here - https://albertherd.com/2019/06/20/c-micro-optimizations-part-1-ref-arguments/
Exploring the performance differences when passing values by ref or by value with structs (value types). The bigger the struct is, the bigger the performance uplift.
When comparing a 16-byte struct, the performance differences when doing work by ref instead of by value is illustrated in the following benchmark. Work by ref exhibit around 72% lift in performance.
Method | limit | Mean | Error | StdDev |
---|---|---|---|---|
BenchmarkIncrementByRef | 1000000 | 1.663 ms | 0.0139 ms | 0.0130 ms |
BenchmarkIncrementByVal | 1000000 | 2.872 ms | 0.0155 ms | 0.0145 ms |
Full description along with IL Analysis can be found in the blog post linked above.