Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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.
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