Created
July 9, 2023 13:40
-
-
Save bellons91/7088fec2e9c2e2369ff4f127fb7487a5 to your computer and use it in GitHub Desktop.
Collection resize benchmark
This file contains 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
#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