Skip to content

Instantly share code, notes, and snippets.

@kshyju
Last active September 21, 2022 16:53
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 kshyju/026fbce09291bbe2fe55d12b45c6b00e to your computer and use it in GitHub Desktop.
Save kshyju/026fbce09291bbe2fe55d12b45c6b00e to your computer and use it in GitHub Desktop.
HashSet constructor vs autogrow benchmarks
[MemoryDiagnoser]
public class CollectionBenchmarks
{
string[] items = new string[] { "hello", "world", "some", "and", "one" };
[Benchmark]
public HashSet<string> AutoGrow()
{
var tpas = new HashSet<string>();
foreach (var tpa in items)
{
tpas.Add(tpa);
}
return tpas;
}
[Benchmark]
public HashSet<string> WithCapacityConstructor()
{
var tpas = new HashSet<string>(items.Length);
foreach (var tpa in tpas)
{
tpas.Add(tpa);
}
return tpas;
}
[Benchmark]
public HashSet<string> WithCollectionConstructor()
{
return new HashSet<string>(items);
}
}
BenchmarkDotNet=v0.13.1, OS=Windows 10.0.22621
11th Gen Intel Core i7-1185G7 3.00GHz, 1 CPU, 8 logical and 4 physical cores
.NET SDK=7.0.100-preview.7.22377.5
  [Host]     : .NET 6.0.9 (6.0.922.41905), X64 RyuJIT
  DefaultJob : .NET 6.0.9 (6.0.922.41905), X64 RyuJIT

Method Mean Error StdDev Gen 0 Gen 1 Allocated
AutoGrow 109.70 ns 1.672 ns 1.396 ns 0.0587 0.0001 368 B
WithCapacityConstructor 25.61 ns 0.295 ns 0.261 ns 0.0408 0.0001 256 B
WithCollectionConstructor 107.14 ns 1.452 ns 1.358 ns 0.0459 - 288 B
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment