Created
December 20, 2024 08:48
-
-
Save ptupitsyn/fe6032544517641c74077aeea16af0ac to your computer and use it in GitHub Desktop.
C# value types vs reference types performance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Linq; | |
using BenchmarkDotNet.Attributes; | |
/// <summary> | |
/// 1M, MB Pro M3 | |
/// | Method | Mean | Error | StdDev | Ratio | | |
/// |------------ |---------:|--------:|--------:|------:| | |
/// | TestValType | 530.2 us | 6.94 us | 6.49 us | 0.98 | | |
/// | TestRefType | 541.1 us | 1.98 us | 1.54 us | 1.00 |. | |
/// | |
/// 1M, Intel Core i9-12900H | |
/// | Method | Mean | Error | StdDev | Ratio | | |
/// |------------ |-----------:|---------:|---------:|------:| | |
/// | TestValType | 417.8 us | 5.77 us | 14.69 us | 0.39 | | |
/// | TestRefType | 1,074.9 us | 14.41 us | 12.04 us | 1.00 |. | |
/// </summary> | |
public class ValueTypeBenchmark | |
{ | |
private const int Count = 1_000_000; | |
private static readonly MyRefType[] RefItems = Enumerable | |
.Range(0, Count) | |
.Select(x => new MyRefType { Field1 = x, Field2 = x + 1 }) | |
.ToArray(); | |
private static readonly MyValType[] ValItems = Enumerable | |
.Range(0, Count) | |
.Select(x => new MyValType { Field1 = x, Field2 = x + 1 }) | |
.ToArray(); | |
[Benchmark] | |
public int TestValType() | |
{ | |
int sum = 0; | |
foreach (var item in ValItems) | |
{ | |
sum += item.Field1 + item.Field2; | |
} | |
return sum; | |
} | |
[Benchmark(Baseline = true)] | |
public int TestRefType() | |
{ | |
int sum = 0; | |
foreach (var item in RefItems) | |
{ | |
sum += item.Field1 + item.Field2; | |
} | |
return sum; | |
} | |
#pragma warning disable | |
public class MyRefType | |
{ | |
public int Field1; | |
public int Field2; | |
} | |
public struct MyValType | |
{ | |
public int Field1; | |
public int Field2; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment