Created
July 27, 2021 15:00
-
-
Save sonnemaf/99ee7b8e48028674db609489ceb52241 to your computer and use it in GitHub Desktop.
Benchmark showing that a record struct with fields can be faster than with properties. Around 9% faster on my PC. If you change decimal to int they are equally fast.
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 BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Running; | |
using System; | |
namespace RecordStructBM { | |
class Program { | |
static void Main(string[] args) { | |
BenchmarkRunner.Run<BM>(); | |
} | |
} | |
public class BM { | |
private readonly PointWithFields _pointWithFields = new PointWithFields(1, 2); | |
private readonly PointWithProperties _pointWithProperties = new PointWithProperties(1, 2); | |
[Benchmark(Baseline = true)] | |
public decimal PointWithFields() { | |
decimal t = 0; | |
for (int i = 0; i < 1000; i++) { | |
t += _pointWithFields.X + _pointWithFields.Y; | |
} | |
return t; | |
} | |
[Benchmark] | |
public decimal PointWithProperties() { | |
decimal t = 0; | |
for (int i = 0; i < 1000; i++) { | |
t += _pointWithProperties.X + _pointWithProperties.Y; | |
} | |
return t; | |
} | |
} | |
readonly record struct PointWithFields { | |
public readonly decimal X; | |
public readonly decimal Y; | |
public PointWithFields(decimal x, decimal y) { | |
X = x; | |
Y = y; | |
} | |
} | |
readonly record struct PointWithProperties(decimal X, decimal Y) { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment