Created
November 18, 2022 10:59
-
-
Save Henr1k80/9edd017ee9fef634901f99fe594d5bb6 to your computer and use it in GitHub Desktop.
Benchmark of CollectionsMarshal.AsSpan
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.Runtime.InteropServices; | |
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Jobs; | |
using BenchmarkDotNet.Reports; | |
using BenchmarkDotNet.Running; | |
Summary? summary = BenchmarkRunner.Run<AsSpanBenchmark>(); | |
[MemoryDiagnoser] | |
[SimpleJob(RuntimeMoniker.Net60)] | |
[SimpleJob(RuntimeMoniker.Net70)] | |
public class AsSpanBenchmark | |
{ | |
private const int NumberToWorkOnSoItIsNotOptimizedAwaySeed = 1337; | |
private static readonly Random Random = new(60); | |
[Params(0, 1, 2, 3, 4)] | |
public ushort ListSize { get; set; } | |
private List<int> _list = new(); | |
[GlobalSetup] | |
public void GlobalSetup() | |
{ | |
_list = new List<int>(ListSize); | |
for (var i = 0; i < ListSize; i++) | |
_list.Add(Random.Next(int.MinValue, int.MaxValue)); | |
} | |
[Benchmark] | |
public int ForEach() | |
{ | |
int numberToWorkOnSoItIsNotOptimizedAway = NumberToWorkOnSoItIsNotOptimizedAwaySeed; | |
foreach (int number in _list) | |
numberToWorkOnSoItIsNotOptimizedAway ^= number; | |
return numberToWorkOnSoItIsNotOptimizedAway; | |
} | |
[Benchmark] | |
public int For() | |
{ | |
int numberToWorkOnSoItIsNotOptimizedAway = NumberToWorkOnSoItIsNotOptimizedAwaySeed; | |
for (var index = 0; index < _list.Count; index++) | |
numberToWorkOnSoItIsNotOptimizedAway ^= _list[index]; | |
return numberToWorkOnSoItIsNotOptimizedAway; | |
} | |
[Benchmark] | |
public int AsSpanForeach() | |
{ | |
int numberToWorkOnSoItIsNotOptimizedAway = NumberToWorkOnSoItIsNotOptimizedAwaySeed; | |
foreach (int number in CollectionsMarshal.AsSpan(_list)) | |
numberToWorkOnSoItIsNotOptimizedAway ^= number; | |
return numberToWorkOnSoItIsNotOptimizedAway; | |
} | |
[Benchmark] | |
public int AsSpanFor() | |
{ | |
int numberToWorkOnSoItIsNotOptimizedAway = NumberToWorkOnSoItIsNotOptimizedAwaySeed; | |
Span<int> span = CollectionsMarshal.AsSpan(_list); | |
for (var index = 0; index < span.Length; index++) | |
numberToWorkOnSoItIsNotOptimizedAway ^= span[index]; | |
return numberToWorkOnSoItIsNotOptimizedAway; | |
} | |
[Benchmark] | |
public int BenchmarkRiderSuggestedLinq() | |
{ | |
return _list.Aggregate(NumberToWorkOnSoItIsNotOptimizedAwaySeed, (current, t) => current ^ t); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results and conclusions can be found here https://www.linkedin.com/pulse/faster-net-list-loops-collectionsmarshalasspan-henrik-gedionsen/