Skip to content

Instantly share code, notes, and snippets.

@usausa
Created October 5, 2020 07:46
Show Gist options
  • Select an option

  • Save usausa/4f5ee39797fa306e0dd21052d4513839 to your computer and use it in GitHub Desktop.

Select an option

Save usausa/4f5ee39797fa306e0dd21052d4513839 to your computer and use it in GitHub Desktop.
namespace ArrayAccessBenchmark50
{
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Exporters;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;
public static class Program
{
public static void Main()
{
BenchmarkRunner.Run<Benchmark>();
}
}
public class BenchmarkConfig : ManualConfig
{
public BenchmarkConfig()
{
AddExporter(MarkdownExporter.Default, MarkdownExporter.GitHub);
AddDiagnoser(MemoryDiagnoser.Default);
AddJob(Job.MediumRun);
}
}
[Config(typeof(BenchmarkConfig))]
public class Benchmark
{
private int[] array = new int[16];
[Benchmark]
public int Single() => array[0];
[Benchmark]
public int SingleByHelper() => ArrayHelper.GetItemReference(array, 0);
[Benchmark]
public int Loop()
{
var total = 0;
for (var i = 0; i < array.Length; i++)
{
total += array[i];
}
return total;
}
[Benchmark]
public int LoopWithCheck()
{
var total = 0;
for (var i = 0; i < 16; i++)
{
total += array[i];
}
return total;
}
[Benchmark]
public int LoopByHelper()
{
var total = 0;
for (var i = 0; i < 16; i++)
{
total += ArrayHelper.GetItemReference(array, i);
}
return total;
}
[Benchmark]
public unsafe int LoopByPointer()
{
var total = 0;
fixed (int* ptr = &array[0])
{
for (var i = 0; i < 16; i++)
{
total += *(ptr + i);
}
}
return total;
}
}
public static class ArrayHelper
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref T GetItemReference<T>(T[] array, int index)
{
ref var data = ref MemoryMarshal.GetArrayDataReference(array);
return ref Unsafe.Add(ref data, index);
}
}
}
BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19041.508 (2004/?/20H1)
Intel Core i5-9500 CPU 3.00GHz, 1 CPU, 6 logical and 6 physical cores
.NET Core SDK=5.0.100-rc.1.20452.10
  [Host]    : .NET Core 5.0.0 (CoreCLR 5.0.20.45114, CoreFX 5.0.20.45114), X64 RyuJIT
  MediumRun : .NET Core 5.0.0 (CoreCLR 5.0.20.45114, CoreFX 5.0.20.45114), X64 RyuJIT

Job=MediumRun  IterationCount=15  LaunchCount=2  
WarmupCount=10  
Method Mean Error StdDev Median Gen 0 Gen 1 Gen 2 Allocated
Single 0.1809 ns 0.0080 ns 0.0115 ns 0.1774 ns - - - -
SingleByHelper 0.0000 ns 0.0000 ns 0.0000 ns 0.0000 ns - - - -
Loop 7.3754 ns 0.0186 ns 0.0272 ns 7.3710 ns - - - -
LoopWithCheck 14.1764 ns 0.1524 ns 0.2282 ns 14.0926 ns - - - -
LoopByHelper 10.6515 ns 0.0229 ns 0.0322 ns 10.6445 ns - - - -
LoopByPointer 6.4811 ns 1.0807 ns 1.4792 ns 7.7960 ns - - - -
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment