Created
February 18, 2024 18:04
-
-
Save ViIvanov/0d3e9b651e663d2c1de8a0bf1d464bab 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.Runtime.InteropServices; | |
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Running; | |
if(args is []) { | |
args = ["--filter", "*"]; | |
}//if | |
BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args); | |
[MemoryDiagnoser] | |
public class Benchmarks | |
{ | |
private static readonly List<string> Input = [.. Enumerable.Range(0, 1000).Select(static item => item.ToString())]; | |
private static readonly string ToCompare = 555.ToString(); | |
[Benchmark(Baseline = true)] | |
public bool EnumerableAny() => Input.Any(static item => item == ToCompare); | |
[Benchmark] | |
public bool ListExists() => Input.Exists(static item => item == ToCompare); | |
[Benchmark] | |
public bool ExtensionsAny() => Input.AsSpan().Any(ToCompare, static (item, state) => item == state); | |
[Benchmark] | |
public bool ManualLoop() { | |
foreach(var item in Input) { | |
if(item == ToCompare) { | |
return true; | |
}//if | |
}//for | |
return false; | |
} | |
} | |
internal static class Extensions | |
{ | |
public static bool Any<TSource, TState>(this Span<TSource> source, TState state, Func<TSource, TState, bool> predicate) { | |
ArgumentNullException.ThrowIfNull(predicate); | |
for(var index = 0; index < source.Length; index++) { | |
if(predicate(source[index], state)) { | |
return true; | |
}//if | |
}//for | |
return false; | |
} | |
public static Span<TSource> AsSpan<TSource>(this List<TSource> source) => CollectionsMarshal.AsSpan(source); | |
} | |
/* | |
| Method | Mean | Error | StdDev | Ratio | Allocated | Alloc Ratio | | |
|-------------- |---------:|----------:|----------:|------:|----------:|------------:| | |
| EnumerableAny | 4.272 us | 0.0518 us | 0.0432 us | 1.00 | 40 B | 1.00 | | |
| ListExists | 1.670 us | 0.0112 us | 0.0099 us | 0.39 | - | 0.00 | | |
| ExtensionsAny | 1.915 us | 0.0307 us | 0.0420 us | 0.45 | - | 0.00 | | |
| ManualLoop | 1.491 us | 0.0118 us | 0.0098 us | 0.35 | - | 0.00 | | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment