Last active
November 29, 2019 03:26
-
-
Save hwada/14c11c09b47e6d4272aa70b92ebed79c to your computer and use it in GitHub Desktop.
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>netcoreapp3.0</TargetFramework> | |
</PropertyGroup> | |
<ItemGroup> | |
<PackageReference Include="BenchmarkDotNet" Version="0.12.0" /> | |
</ItemGroup> | |
</Project> |
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; | |
using System.Linq; | |
using BenchmarkDotNet.Attributes; | |
namespace ArrayRangePerformance | |
{ | |
[MemoryDiagnoser] | |
public class ArraySum | |
{ | |
private const int Count = 100000000; | |
public readonly long[] _array = Enumerable.Range(0, Count).Select(x => (long)x).ToArray(); | |
public readonly int _start = 99; | |
public readonly int _stop = Count - 1; | |
[Benchmark] | |
public long Sum_Index() | |
{ | |
var sum = 0L; | |
for (var i = _start; i < _stop; i++) | |
{ | |
sum += _array[i]; | |
} | |
return sum; | |
} | |
[Benchmark] | |
public long Sum_Linq() | |
{ | |
return _array.Skip(_start).Take(_stop - _start).Sum(); | |
} | |
[Benchmark] | |
public long Sum_Range() | |
{ | |
return _array[_start.._stop].Sum(); | |
} | |
[Benchmark] | |
public long Sum_Span() | |
{ | |
var sum = 0L; | |
foreach (var n in _array.AsSpan(_start.._stop)) | |
{ | |
sum += n; | |
} | |
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
using BenchmarkDotNet.Running; | |
namespace ArrayRangePerformance | |
{ | |
class Program | |
{ | |
static void Main() | |
{ | |
BenchmarkRunner.Run<ArraySum>(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment