Skip to content

Instantly share code, notes, and snippets.

@bellons91
Created July 9, 2023 13:40
Show Gist options
  • Save bellons91/7088fec2e9c2e2369ff4f127fb7487a5 to your computer and use it in GitHub Desktop.
Save bellons91/7088fec2e9c2e2369ff4f127fb7487a5 to your computer and use it in GitHub Desktop.
Collection resize benchmark
#LINQPad optimize+
void Main()
{
var summary = BenchmarkRunner.Run<HashSetPerformance>();
}
[MemoryDiagnoser]
public class HashSetPerformance
{
[Params(100, 1000, 10000, 100_000)]
public int CollectionSize;
[Benchmark]
public void SizeDefined()
{
int itemsCount = CollectionSize;
HashSet<int> set = new HashSet<int>(itemsCount);
foreach (var i in Enumerable.Range(0, itemsCount))
{
set.Add(i);
}
}
[Benchmark]
public void SizeDefinedWithEnsureCapacity()
{
int itemsCount = CollectionSize;
HashSet<int> set = new HashSet<int>();
set.EnsureCapacity(itemsCount);
foreach (var i in Enumerable.Range(0, itemsCount))
{
set.Add(i);
}
}
[Benchmark]
public void SizeNotDefined()
{
int itemsCount = CollectionSize;
HashSet<int> set = new HashSet<int>();
foreach (var i in Enumerable.Range(0, itemsCount))
{
set.Add(i);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment