Created
April 6, 2021 05:02
-
-
Save jl0pd/7501c6d1143e6c0c5886a5949de00aea to your computer and use it in GitHub Desktop.
C# Unsafe and semi-safe sum
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 System.Collections.Generic; | |
using System.Linq; | |
using System.Runtime.CompilerServices; | |
using System.Runtime.InteropServices; | |
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Running; | |
namespace SumTest | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
BenchmarkRunner.Run<TestSafeAndUnsafeSum>(); | |
} | |
} | |
[DisassemblyDiagnoser] | |
public class TestSafeAndUnsafeSum | |
{ | |
public IEnumerable<object[]> Data() | |
{ | |
yield return new object[] { Enumerable.Range(0, 100_000).ToArray(), 100_000 }; | |
yield return new object[] { Enumerable.Range(0, 1_000_000).ToArray(), 1_000_000 }; | |
yield return new object[] { Enumerable.Range(0, 10_000_000).ToArray(), 10_000_000 }; | |
} | |
[Benchmark] | |
[MethodImpl(MethodImplOptions.NoInlining)] | |
[ArgumentsSource(nameof(Data))] | |
public int SumDirect(int[] ints, int length) | |
{ | |
int sum = 0; | |
for (int i = 0; i < ints.Length; i++) | |
{ | |
sum += ints[i]; | |
} | |
return sum; | |
} | |
[MethodImpl(MethodImplOptions.AggressiveInlining)] | |
static T FastAccessValue<T>(T[] ar, int index) | |
{ | |
ref T tableRef = ref MemoryMarshal.GetArrayDataReference(ar); | |
return Unsafe.Add(ref tableRef, (nint)index); | |
} | |
[Benchmark] | |
[MethodImpl(MethodImplOptions.NoInlining)] | |
[ArgumentsSource(nameof(Data))] | |
public int SumUnsafe(int[] ints, int length) | |
{ | |
int sum = 0; | |
for (int i = 0; i < length; i++) | |
{ | |
sum += FastAccessValue(ints, i); | |
} | |
return sum; | |
} | |
} | |
} |
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
<Project Sdk="Microsoft.NET.Sdk"> | |
<PropertyGroup> | |
<OutputType>Exe</OutputType> | |
<TargetFramework>net5.0</TargetFramework> | |
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> | |
</PropertyGroup> | |
<ItemGroup> | |
<PackageReference Include="BenchmarkDotNet" Version="0.12.1" /> | |
</ItemGroup> | |
</Project> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run result