Skip to content

Instantly share code, notes, and snippets.

@bellons91
Created July 9, 2023 13:41
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 bellons91/3a51f7f180e299be921c0757cd6a6f08 to your computer and use it in GitHub Desktop.
Save bellons91/3a51f7f180e299be921c0757cd6a6f08 to your computer and use it in GitHub Desktop.
Distinct vs HashSet benchmark
#LINQPad optimize+
void Main()
{
var summary = BenchmarkRunner.Run<DuplicatePerformance>();
}
[MemoryDiagnoser]
public class DuplicatePerformance
{
private List<int> items;
[Params(2, 100, 1000)]
public int SetSize;
[GlobalSetup]
public void GlobalSetup()
{
Random rd = new Random();
items = Enumerable.Range(0, SetSize)
.Select(e => rd.Next(0, SetSize))
.ToList();
}
[Benchmark]
public int DuplicateInFor()
{
List<int> noDuplicates = new List<int>();
for (int i = 0; i < items.Count; i++)
{
int element = items[i];
if (!noDuplicates.Contains(element))
noDuplicates.Add(element);
}
return noDuplicates.Count;
}
[Benchmark]
public int DuplicateInForeach()
{
List<int> noDuplicates = new List<int>();
foreach (var element in items)
{
if (!noDuplicates.Contains(element))
noDuplicates.Add(element);
}
return noDuplicates.Count;
}
[Benchmark]
public int DuplicateWithDistinct()
{
List<int> noDuplicates = items.Distinct().ToList();
return noDuplicates.Count;
}
[Benchmark]
public int DuplicateWithHashSet()
{
List<int> noDuplicates = items.ToHashSet().ToList();
return noDuplicates.Count;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment