Using The EnsureCapacity Method In C# Lists, Queues And Stacks

Introduction

In today’s article we will take a look at a new feature that has been introduced in C# 10. This is the EnsureCapacity method that has been added to the List, Queue, and Stack collections. We will discuss why we should use this method and when.

So, let us begin.

Why and when to use the EnsureCapacity method

We will start by looking at why we need to use this method and when. Internally, an array is used by the List, Queue, and Stack collections. Each time we add more items to these collections, we need to increase the size of this internal array. Hence, there is a resizing operation that takes place. This is a performance hit as the array is changing its size. In a situation where we know the maximum size of this array or let’s say we know the maximum elements that will be stored in our List, Queue, or Stack collection, we can preset the size by using the EnsureCapacity method. This will ensure that this size is set initially and there would be no resizing of the internal array and hence we get a performance boost. Let, us implement this in a test application,

Creating a console application to test the EnsureCapacity method

We will start by creating a C# console application in Visual Studio 2022 community edition as below,

Using the EnsureCapacity method in Cshaarp Lists, Queues and Stacks

Using the EnsureCapacity method in Cshaarp Lists, Queues and Stacks

Using the EnsureCapacity method in Cshaarp Lists, Queues and Stacks

Using the EnsureCapacity method in Cshaarp Lists, Queues and Stacks

Using the EnsureCapacity method in Cshaarp Lists, Queues and Stacks

Replace the Program.cs file with the below code,

var thisList = new List < int > ();
thisList.EnsureCapacity(5);
for (var i = 0; i < 5; i++) {
    thisList.Add(i);
    Console.WriteLine(thisList[i]);
}
thisList.Add(5);
Console.WriteLine(thisList[5]);

When we run this code, we see the below output.

Using the EnsureCapacity method in Cshaarp Lists, Queues and Stacks

Hence, we see that even if we exceed the capacity defined in the EnsureCapacity method, we can still keep adding elements to our list. However, at this point, the internal array is back to resizing and we have lost the performance gain. This indicates that we must be very careful when setting the EnsureCapacity value.

Summary

In this article, we took a look at using the EnsureCapacity method with the List collection in C# 10. We discussed the advantages of using this method and when it should be used. The same applies to the Queue and Stack collections. Happy coding!