Is C# compiler that smart or am I benchmarking wrong?
intermediateadvanced
Hi, I wanted to see what is faster: accessing
SomeClass.Field
SomeClass.Field
or
SomeClass.NestedClass.Field
SomeClass.NestedClass.Field
To do it I wrote simple benchmark:
using BenchmarkDotNet.Attributes;using BenchmarkDotNet.Running;BenchmarkRunner.Run<AccessBenchmark>();class Flat { public int Value { get; set; } }class Nested { public Flat Flat { get; set; } }public class AccessBenchmark { private const int N = 100000; private const int MaxValue = int.MaxValue / N; private readonly Random random = new(); private readonly Flat[] flats; private readonly Nested[] nesteds; public AccessBenchmark() { flats = new Flat[N]; nesteds = new Nested[N]; for (var i = 0; i < N; i++) { flats[i] = new Flat { Value = random.Next(MaxValue) }; nesteds[i] = new Nested { Flat = new Flat { Value = random.Next(MaxValue) } }; } } [Benchmark] public int Flat() => flats.Sum(x => x.Value); [Benchmark] public int Nested() => nesteds.Sum(x => x.Flat.Value);}
using BenchmarkDotNet.Attributes;using BenchmarkDotNet.Running;BenchmarkRunner.Run<AccessBenchmark>();class Flat { public int Value { get; set; } }class Nested { public Flat Flat { get; set; } }public class AccessBenchmark { private const int N = 100000; private const int MaxValue = int.MaxValue / N; private readonly Random random = new(); private readonly Flat[] flats; private readonly Nested[] nesteds; public AccessBenchmark() { flats = new Flat[N]; nesteds = new Nested[N]; for (var i = 0; i < N; i++) { flats[i] = new Flat { Value = random.Next(MaxValue) }; nesteds[i] = new Nested { Flat = new Flat { Value = random.Next(MaxValue) } }; } } [Benchmark] public int Flat() => flats.Sum(x => x.Value); [Benchmark] public int Nested() => nesteds.Sum(x => x.Flat.Value);}
Results show that there is very little difference between two methods:
| Method | Mean | Error | StdDev ||------- |---------:|--------:|--------:|| Flat | 218.8 us | 2.96 us | 2.77 us | | Nested | 200.2 us | 3.89 us | 5.70 us |
| Method | Mean | Error | StdDev ||------- |---------:|--------:|--------:|| Flat | 218.8 us | 2.96 us | 2.77 us | | Nested | 200.2 us | 3.89 us | 5.70 us |
Is my benchmark wrong or C# compiler is able to optimize such things?