Why List Size Matters in C# Applications?

Do you know that List<T> accepts size parameter and its impact the performance?
Yes, the size of a List<T> can impact performance, especially when adding elements to the list. When a List<T> reaches its capacity, it has to allocate a new internal array that is twice the size of the original array and copy all the elements from the original array to the new array. This can be an expensive operation, especially if the list is large.

To mitigate this issue, you can set the initial capacity of the list when you create it, using the constructor that takes an int parameter. This can help to reduce the number of reallocations and copying operations that are needed as elements are added to the list.

Another way to improve performance is to use a different data structure that has better performance characteristics for the specific use case. For example, if you need to store a large number of elements and frequently add or remove elements at the beginning or middle of the list, a LinkedList<T> may be a better choice than a List<T>. On the other hand, if you frequently access elements by index, a List<T> may be a better choice.

In general, it’s a good idea to choose the data structure that best fits the specific requirements of your use case, and to monitor performance and adjust the data structure or algorithm as needed.

Let’s say we have two lists, one initialized with a capacity of 100 and the other without a specified capacity:

List<int> list1 = new List<int>(100); // Capacity of 100
List<int> list2 = new List<int>(); // Default capacity (0)

Now let’s add 10000 integers to both lists:

Stopwatch stopwatch = new Stopwatch();

for (int i = 0; i < 10000; i++)

Console.WriteLine($"Time taken for list1: {stopwatch.ElapsedMilliseconds} ms");


for (int i = 0; i < 10000; i++)

Console.WriteLine($"Time taken for list2: {stopwatch.ElapsedMilliseconds} ms");

This code will add 10000 integers to both lists and measure the time taken to do so. The output will look something like this:

Time taken for list1: 0 ms
Time taken for list2: 8 ms

As you can see, list1, which had an initial capacity of 1000, was able to add all 10000 integers without having to resize its internal array. On the other hand, list2 had to resize its internal array multiple times during the process, which resulted in slower performance.

This example shows that initializing a list with an appropriate capacity can improve performance by reducing the number of times the list needs to resize its internal array.

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads