Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<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
You can’t perform that action at this time.