Skip to content

Instantly share code, notes, and snippets.

@Joe4evr
Created November 12, 2020 13:38
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 Joe4evr/4f45b342ff3ef7b46ed0e622ab198274 to your computer and use it in GitHub Desktop.
Save Joe4evr/4f45b342ff3ef7b46ed0e622ab198274 to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
using System.Linq;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
[SimpleJob(RuntimeMoniker.NetCoreApp31)]
[SimpleJob(RuntimeMoniker.NetCoreApp50)]
public class ArrayVsListEnumeration
{
private readonly List<LargeStruct> _largeStructsList = Enumerable.Range(1, 16).Select(i => new LargeStruct(i)).ToList();
private readonly LargeStruct[] _largeStructArray = Enumerable.Range(1, 16).Select(i => new LargeStruct(i)).ToArray();
private readonly List<SmallClass> _classList = Enumerable.Range(1, 16).Select(i => new SmallClass(i)).ToList();
private readonly SmallClass[] _classArray = Enumerable.Range(1, 16).Select(i => new SmallClass(i)).ToArray();
private readonly List<int> _intList = Enumerable.Range(1, 16).ToList();
private readonly int[] _intArray = Enumerable.Range(1, 16).ToArray();
[Benchmark]
public int LargeStructList()
{
int counter = 0;
foreach (var item in _largeStructsList)
{
counter += item.Index;
}
return counter;
}
[Benchmark]
public int LargeStructArray()
{
int counter = 0;
foreach (var item in _largeStructArray)
{
counter += item.Index;
}
return counter;
}
[Benchmark]
public int ClassList()
{
int counter = 0;
foreach (var item in _classList)
{
counter += item.Index;
}
return counter;
}
[Benchmark]
public int ClassArray()
{
int counter = 0;
foreach (var item in _classArray)
{
counter += item.Index;
}
return counter;
}
[Benchmark]
public int IntList()
{
int counter = 0;
foreach (var item in _intList)
{
counter += item;
}
return counter;
}
[Benchmark]
public int IntArray()
{
int counter = 0;
foreach (var item in _intArray)
{
counter += item;
}
return counter;
}
}
public unsafe struct LargeStruct
{
public int Index { get; }
private fixed byte _array[60]; //Pad this struct to 64 bytes
public LargeStruct(int index)
{
Index = index;
}
}
public sealed class SmallClass
{
public int Index { get; }
public SmallClass(int index)
{
Index = index;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment