Skip to content

Instantly share code, notes, and snippets.

@tdkkdt
Last active December 23, 2018 18:34
Show Gist options
  • Save tdkkdt/181e3f1e2ee6bb1ce1662bfae1241545 to your computer and use it in GitHub Desktop.
Save tdkkdt/181e3f1e2ee6bb1ce1662bfae1241545 to your computer and use it in GitHub Desktop.
List vs Array
using System.Collections.Generic;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
namespace ConsoleApp2 {
[LegacyJitX64Job, LegacyJitX86Job, RyuJitX64Job]
public class Benchmark {
[Params(10, 100, 1000, 10000, 100000, 1000000)]
public int ItemsCount { get; set; }
public int[] array;
public List<int> list;
[IterationSetup]
public void IterationSetup() {
array = new int[ItemsCount];
list = new List<int>(array);
}
[Benchmark(Baseline = true)]
public int ForEachArrayAsArray() => ForEachArrayAsArrayCore(array);
[Benchmark]
public int ForEachArrayAsIEnumerable() => ForEachAsIEnumerableCore(array);
[Benchmark]
public int ForEachListAsList() => ForEachListAsListCore(list);
[Benchmark]
public int ForEachListAsIEnumerable() => ForEachAsIEnumerableCore(list);
int ForEachArrayAsArrayCore(int[] a) {
int sum = 0;
foreach (int i in a) {
sum += i;
}
return sum;
}
int ForEachAsIEnumerableCore(IEnumerable<int> a) {
int sum = 0;
foreach (int i in a) {
sum += i;
}
return sum;
}
int ForEachListAsListCore(List<int> a) {
int sum = 0;
foreach (int i in a) {
sum += i;
}
return sum;
}
}
class Program {
static void Main(string[] args) {
BenchmarkRunner.Run<Benchmark>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment