Created
February 13, 2024 15:32
-
-
Save teoadal/e039d2423c8984747f2372e048dca931 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
using System; | |
using System.Linq; | |
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Jobs; | |
namespace Benchmarks.CollectionBenchmarks; | |
[SimpleJob(RuntimeMoniker.Net80)] | |
[MeanColumn, MemoryDiagnoser] | |
public class ArrayCopy | |
{ | |
[Benchmark(Baseline = true)] | |
public int Framework() | |
{ | |
Array.Copy(_array, _result, _array.Length); | |
return _result[0] % 2; | |
} | |
[Benchmark] | |
public int Manual() | |
{ | |
for (var i = _array.Length - 1; i >= 0; i--) | |
{ | |
_result[i] = _array[i]; | |
} | |
return _array[0] % 2; | |
} | |
[Benchmark] | |
public int ManualBuffer() | |
{ | |
Span<int> buffer = stackalloc int[256]; | |
var bufferIndex = 0; | |
var bufferLength = buffer.Length; | |
var part = 0; | |
foreach (var element in _array) | |
{ | |
buffer[bufferIndex++] = element; | |
if (bufferIndex < bufferLength) continue; | |
var target = _result.AsSpan(bufferIndex * part, bufferLength); | |
part++; | |
buffer.CopyTo(target); | |
bufferIndex = 0; | |
} | |
return _array[0] % 2; | |
} | |
private int[] _array = null!; | |
private int[] _result = null!; | |
[GlobalSetup] | |
public void Init() | |
{ | |
_array = Enumerable.Range(0, 10_000).ToArray(); | |
_result = new int[_array.Length]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment