Skip to content

Instantly share code, notes, and snippets.

@mcliment
Last active December 17, 2023 11:18
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mcliment/4690433 to your computer and use it in GitHub Desktop.
Save mcliment/4690433 to your computer and use it in GitHub Desktop.
Test to check the speed of List.ForEach vs List.AddRange
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);
}
}
}
}
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