Skip to content

Instantly share code, notes, and snippets.

@nishanc
Created December 12, 2021 13:44
Show Gist options
  • Save nishanc/32aa2f1d2c6dd0bf9a9f5195f2beeb74 to your computer and use it in GitHub Desktop.
Save nishanc/32aa2f1d2c6dd0bf9a9f5195f2beeb74 to your computer and use it in GitHub Desktop.
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
namespace SpanTDemo
{
class Program
{
static void Main(string[] args)
{
BenchmarkRunner.Run<BenchmarkDemo1>();
}
}
[MemoryDiagnoser]
public class BenchmarkDemo1
{
private int[] _myArray;
[Params(100, 1000, 10000)]
public int Size { get; set; }
[GlobalSetup]
public void SetUp()
{
_myArray = new int[Size];
for (int index = 0; index < Size; index++)
{
_myArray[index] = index;
}
}
[Benchmark(Baseline = true)]
public int[] Original()
{
return _myArray.Skip(Size / 2).Take(Size / 4).ToArray();
}
[Benchmark]
public int[] ArrayCopy()
{
var copy = new int[Size / 4];
Array.Copy(_myArray, Size / 2, copy, 0, Size / 4);
return copy;
}
[Benchmark]
public Span<int> Span()
{
return _myArray.AsSpan().Slice(Size / 2, Size / 4);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment