Method | Mean | Error | StdDev | Ratio | RatioSD |
---|---|---|---|---|---|
Class | 747.2 ns | 14.93 ns | 13.23 ns | 1.00 | 0.00 |
Structs | 572.7 ns | 1.25 ns | 1.17 ns | 0.77 | 0.01 |
StructsRo | 831.8 ns | 4.39 ns | 4.11 ns | 1.11 | 0.02 |
Created
June 29, 2021 21:30
-
-
Save MichalBrylka/5a94af4aad95425d34a06e61e1c8ea58 to your computer and use it in GitHub Desktop.
This file contains hidden or 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; | |
using System.Linq; | |
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Running; | |
// ReSharper disable InconsistentNaming | |
namespace StructBench | |
{ | |
class Program | |
{ | |
static void Main(string[] args) => BenchmarkRunner.Run<StructVsClass>(); | |
} | |
public class StructVsClass | |
{ | |
const int LEN = 1000; | |
private static readonly StructP3[] _structs = new StructP3[LEN]; | |
private static readonly StructP3Ro[] _structsRo = new StructP3Ro[LEN]; | |
private static readonly ClassP3[] _classes = Enumerable.Range(0, LEN).Select(_ => new ClassP3()).ToArray(); | |
[Benchmark(Baseline = true)] | |
public int Class() | |
{ | |
for (int i = 0; i < LEN; i++) | |
_classes[i].X += i; | |
return 42; | |
} | |
[Benchmark] | |
public int Structs() | |
{ | |
Span<StructP3> arr = _structs; | |
for (int i = 0; i < LEN; i++) | |
arr[i].X += i; | |
return 42; | |
} | |
[Benchmark] | |
public int StructsRo() | |
{ | |
Span<StructP3Ro> arr = _structsRo; | |
for (int i = 0; i < LEN; i++) | |
{ | |
(int x, int y, int z) = arr[i]; | |
arr[i] = new StructP3Ro(x + i, y, z); | |
} | |
return 42; | |
} | |
} | |
class ClassP3 | |
{ | |
public int X; | |
public int Y; | |
public int Z; | |
} | |
struct StructP3 | |
{ | |
public int X; | |
public int Y; | |
public int Z; | |
} | |
readonly struct StructP3Ro | |
{ | |
public readonly int X; | |
public readonly int Y; | |
public readonly int Z; | |
public StructP3Ro(int x, int y, int z) | |
{ | |
X = x; | |
Y = y; | |
Z = z; | |
} | |
public void Deconstruct(out int x, out int y, out int z) | |
{ | |
x = X; | |
y = Y; | |
z = Z; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment