Resizing a Generic List

One of the main benefit of using Generic List to Array is it convenience to Add new items without exposing the re-initialization details. However, if you are a person who counts ticks, and nanoseconds and if you are obsessed about memory usage then it is important to understand what is happening the in background when a new item is added to a generic list.

When you create a new Generic List, with no capacity specified, it will first create an empty array. And when you add the first element the size of the background array is updated to 4. And when no.of items reaches the size of the background array, the array is copied to a new array with a size double to the current size. This process of creation of new array, copying the existing values causes additional pressure to Garbage Collector and to the CPU and is not an ideal approach if the size of the collection is already known.

'Sample code to initialize a generic list with capacity specified.
Dim capacity As Integer = 10000
Dim collection As New List(Of Integer)(capacity)

If you don’t know the size of the collection during the construction of the Generic List. You can set the Capacity property of the Generic List. Whenever you set this property to a higher value than of the size of the background array, the array is copied to a new array with the size specified.

'Sample code to initialize generic list and capacity specified later
Dim collection2 As New List(Of String)
collection2.Capacity = 30000

Hence, if the length of the Generic List can be determined without causing much computation efforts or memory usage, it is always better to specify the capacity of List.


Image Credits goes to : http://www.flickr.com/photos/jemsweb

2 thoughts on “Resizing a Generic List

Add yours

    1. The point is not about using List(Of T) the point is when the size is known it is always better to specify the capacity for better performance.

Leave a comment

Blog at WordPress.com.

Up ↑