Created
July 25, 2020 14:15
-
-
Save aalmada/373ed85a56d5a6edb77331f510209320 to your computer and use it in GitHub Desktop.
This file contains hidden or 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.Attributes; | |
using System; | |
using System.Linq; | |
namespace ConsoleApp2 | |
{ | |
[MemoryDiagnoser] | |
[DisassemblyDiagnoser(printSource: true)] | |
public class ArrayBenchmarks | |
{ | |
int[] array; | |
ReadOnlyMemory<int> memory; | |
[Params(100)] | |
public int Count { get; set; } | |
[GlobalSetup] | |
public void GlobalSetup() | |
{ | |
array = Enumerable.Range(0, Count).ToArray(); | |
memory = array.AsMemory(); | |
} | |
[Benchmark(Baseline = true)] | |
public int Enumerator() | |
{ | |
var sum = 0; | |
foreach (var item in array) | |
sum += item; | |
return sum; | |
} | |
[Benchmark] | |
public int Indexer() | |
{ | |
var sum = 0; | |
for (var index = 0; index < array.Length; index++) | |
sum += array[index]; | |
return sum; | |
} | |
[Benchmark] | |
public int IndexerVar() | |
{ | |
var sum = 0; | |
var length = array.Length; | |
for (var index = 0; index < length; index++) | |
sum += array[index]; | |
return sum; | |
} | |
[Benchmark] | |
public int Span() | |
{ | |
var span = memory.Span; | |
var sum = 0; | |
for (var index = 0; index < span.Length; index++) | |
sum += span[index]; | |
return sum; | |
} | |
[Benchmark] | |
public int Memory() | |
{ | |
var sum = 0; | |
for (var index = 0; index < memory.Length; index++) | |
sum += memory.Span[index]; | |
return sum; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment