C# HashSet vs List: A Performance Analysis on Add Operations
When it comes to choosing between a HashSet and a List in C#, performance is often a critical factor. Both collections have their strengths, but they excel in different scenarios. This article delves into the performance aspects of adding elements to these collections, helping you make an informed decision.
Understanding the Basics
Before we dive into performance, let's quickly recap the basics.
-
HashSet: A set of values that does not allow duplicates. It is implemented as a hash table, providing fast average-case performance for add, remove, and contains operations.

List: A dynamic array that allows duplicate elements. It provides fast access to elements by index but can be slower for add and remove operations, especially in the middle of the list.
Add Operation Performance: HashSet vs List
The performance of add operations in HashSet and List differs significantly due to their internal implementations.
HashSet: Fast and Consistent
The HashSet uses a hash table under the hood, which allows it to add elements in constant average time, O(1). This means the time taken to add an element doesn't change significantly regardless of the size of the collection. Here's a simple demonstration:

HashSet<int> hashSet = new HashSet<int>();
for (int i = 0; i < 1000000; i++)
{
hashSet.Add(i);
}
List: Varying Performance
The List, being a dynamic array, also provides fast add operations at the end (amortized O(1)). However, adding elements in the middle of the list can be costly, as it may require resizing and shifting elements (O(n)). Here's an example:
List<int> list = new List<int>();
for (int i = 0; i < 1000000; i++)
{
list.Add(i);
}
In this case, adding elements in the middle would look like this:
list.Insert(500000, 999999);
This operation can be significantly slower, especially for large lists.

Benchmarking: The Proof is in the Performance
To illustrate the performance difference, let's benchmark adding one million elements to both collections.
| Collection | Operation | Average Time (ms) |
|---|---|---|
HashSet<int> |
Add | 15 |
List<int> |
Add | 15 |
List<int> |
Insert (middle) | 120 |
As you can see, adding elements to a HashSet is consistently fast, while adding elements to the middle of a List can be significantly slower.
When to Use Each Collection
Given the performance differences, when should you use each collection?
-
Use
HashSetwhen:
- You need to ensure no duplicate elements.
- Performance of add, remove, and contains operations is critical.
Use List when:
- You need to access elements by index.
- Adding elements at the end is sufficient.
Remember, the best collection to use depends on your specific use case and requirements.






















