Skip to content

Instantly share code, notes, and snippets.

@tkouba
Created April 4, 2024 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tkouba/01ee749954a63213499b44c383147a79 to your computer and use it in GitHub Desktop.
Save tkouba/01ee749954a63213499b44c383147a79 to your computer and use it in GitHub Desktop.
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