-
-
Save skynode/7d9c9595ac73bca5dc5fb50223c21426 to your computer and use it in GitHub Desktop.
Test to check the speed of List.ForEach vs List.AddRange
This file contains hidden or 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 System; | |
using System.Collections.Generic; | |
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Attributes.Jobs; | |
namespace ForEachVsAddRange | |
{ | |
[MemoryDiagnoser] | |
public class Benchmark | |
{ | |
private List<string> _list; | |
private List<string> _toAdd; | |
private const int Loops = 1000; | |
private readonly Random _rand = new Random(42); | |
[Params(100, 1000, 10000)] | |
public int ListSize { get; set; } | |
[Setup] | |
public void Setup() | |
{ | |
_list = new List<string>(Loops * ListSize); | |
_toAdd = new List<string>(ListSize); | |
for (var i = 0; i < ListSize; i++) | |
{ | |
_toAdd.Add(new string('=', _rand.Next(1, 10000))); | |
} | |
} | |
[Benchmark(Baseline = true)] | |
public void ClassicLoop() | |
{ | |
_list.Clear(); | |
for (var i = 0; i < Loops; i++) | |
{ | |
for (var j = 0; j < ListSize; j++) | |
{ | |
_list.Add(_toAdd[j]); | |
} | |
} | |
} | |
[Benchmark] | |
public void ForEach() | |
{ | |
_list.Clear(); | |
for (var i = 0; i < Loops; i++) | |
{ | |
_toAdd.ForEach(_list.Add); | |
} | |
} | |
[Benchmark] | |
public void AddRange() | |
{ | |
_list.Clear(); | |
for (var i = 0; i < Loops; i++) | |
{ | |
_list.AddRange(_toAdd); | |
} | |
} | |
} | |
} |
This file contains hidden or 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.Running; | |
namespace ForEachVsAddRange | |
{ | |
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