Skip to content

Instantly share code, notes, and snippets.

@hwada
Last active November 29, 2019 03:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hwada/14c11c09b47e6d4272aa70b92ebed79c to your computer and use it in GitHub Desktop.
Save hwada/14c11c09b47e6d4272aa70b92ebed79c to your computer and use it in GitHub Desktop.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.12.0" />
</ItemGroup>
</Project>
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;
}
}
}
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