5

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

Community
  • 1
  • 1
Cristian Garcia
  • 9,630
  • 6
  • 54
  • 75

2 Answers2

4

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

  • 4
    According to MSDN List.Add() and HashSet.Add() both are O(1) if count is less than the capacity of the internal array and O(n) if the object needs to be resized. – Almis Jan 16 '18 at 12:34
1

HashSet should be used in case when you care about the performance (especially if you know that you will operate on a large set of items) but do not care about the order.

Use List when you want to iterate through the collection. Iterating through all the items in a List it is generally much faster than through a set (unless you use inside such methods as Contains).

Check this sample for test the performance:

const int COUNT = 100000;
        HashSet<int> hashSetOfInts = new HashSet<int>();
        Stopwatch stopWatch = new Stopwatch();
        for (int i = 0; i < COUNT; i++)
        {
            hashSetOfInts.Add(i);
        }

        stopWatch.Start();
        for (int i = 0; i < COUNT; i++)
        {
            hashSetOfInts.Contains(i);
        }
        stopWatch.Stop();

        Console.WriteLine(stopWatch.Elapsed);

        stopWatch.Reset();
        List<int> listOfInts = new List<int>();
        for (int i = 0; i < COUNT; i++)
        {
            listOfInts.Add(i);
        }

        stopWatch.Start();
        for (int i = 0; i < COUNT; i++)
        {
            listOfInts.Contains(i);
        }
        stopWatch.Stop();

        Console.WriteLine(stopWatch.Elapsed);
        Console.Read();
Seminda
  • 1,745
  • 12
  • 15