Skip to content

Instantly share code, notes, and snippets.

@Trapov
Created May 5, 2019 11:44
Show Gist options
  • Save Trapov/481e412f1b44803b287096e00aef92e8 to your computer and use it in GitHub Desktop.
Save Trapov/481e412f1b44803b287096e00aef92e8 to your computer and use it in GitHub Desktop.
ForVsForeach
namespace ForVsForeach
{
using System.Buffers;
using System;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;
using System.Collections.Generic;
public static class Program
{
[CoreJob]
[RankColumn, MemoryDiagnoser]
public class ForeachVsFor
{
public byte[] _data;
[Params(100, 10000)]
public int N;
[GlobalSetup]
public void Setup()
{
_data = ArrayPool<byte>.Shared.Rent(N);
new Random(42).NextBytes(_data);
}
[Benchmark]
public void Foreach()
{
var list = new List<byte>();
foreach(var d in _data)
list.Add(d);
}
[Benchmark]
public void For()
{
var list = new List<byte>();
for(var i = 0; i < N; i++)
list.Add(_data[i]);
}
}
public static void Main(string[] args)
{
BenchmarkRunner.Run<ForeachVsFor>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment