Created
April 4, 2024 08:49
-
-
Save tkouba/01ee749954a63213499b44c383147a79 to your computer and use it in GitHub Desktop.
More benchmarks on https://www.youtube.com/watch?v=jmmz1cInNow&ab_channel=NickChapsas
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 BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Running; | |
namespace ForBenchmark | |
{ | |
[MemoryDiagnoser(false)] | |
public class Program | |
{ | |
[Params(10, 1000)] | |
public int MAX { get; set; } | |
[Benchmark(Baseline = true)] | |
public void ClassicFor() | |
{ | |
for(int i = 0; i < MAX; i++) | |
{ | |
DoSomething(i); | |
} | |
} | |
[Benchmark] | |
public void ForEachCustomEnumerator() | |
{ | |
foreach (var i in 1..MAX) | |
{ | |
DoSomething(i); | |
} | |
} | |
[Benchmark] | |
public void EnumerableRange() | |
{ | |
foreach (var i in Enumerable.Range(1, MAX)) | |
{ | |
DoSomething(i); | |
} | |
} | |
[Benchmark] | |
public void EnumerableRangeListForEach() | |
{ | |
Enumerable.Range(1, MAX).ToList().ForEach(i => DoSomething(i)); | |
} | |
void DoSomething(int i) { } | |
static void Main(string[] args) | |
{ | |
var summary = BenchmarkRunner.Run(typeof(Program).Assembly); | |
} | |
} | |
public static class Extensions | |
{ | |
public static CustomIntEnumerator GetEnumerator(this Range range) | |
=> new CustomIntEnumerator(range); | |
} | |
public ref struct CustomIntEnumerator | |
{ | |
private int _current; | |
private readonly int _end; | |
public CustomIntEnumerator(Range range) | |
{ | |
if (range.End.IsFromEnd) | |
throw new NotSupportedException(); | |
_current = range.Start.Value - 1; | |
_end = range.End.Value; | |
} | |
public int Current => _current; | |
public bool MoveNext() | |
{ | |
_current++; | |
return _current <= _end; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment