Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List.Add vs HashSet.Add for small collections in c#

Given

HashSet<T> set;
List<T> list;
T t;

Which of these performs better for SMALL collections?

if (! list.Contains (t)) list.Add (t);

Or

set.Add (t);

Source of doubt: HashSet vs. List performance

like image 393
Cristian Garcia Avatar asked Sep 30 '22 23:09

Cristian Garcia


1 Answers

It really has to do with how you are going to use the data structures. If you need to access an item using an index, then you can't use a HashSet, also if you need to store duplicates, you can;t use HashSet. A List is typically used for most operations, so I you don't understand the underlying design and functionality of the HashSet, then chances are a List will suffice.enter image description here

like image 151
Dustin Falgout Avatar answered Oct 13 '22 12:10

Dustin Falgout