C # General list with default size or delivery

I am wondering if there is a difference (in terms of performance, memory preservation) to define a list with a default size or specify it.

List<object> m_objects = new List<object>(); or List<object> m_objects = new List<object>(100); 

Both will increase in size by doubling if more elements are added, right?

Thanks,

+4
source share
4 answers

If you know that you will have more than 100 items, the second is faster.

Each time it "doubles", it must copy the contents of the entire existing array. For large lists, this can be slow.
If you specify a capacity, it will not change at all until it becomes larger than you indicated.

If you never add more than 100 elements, it just takes up a bit of memory (in particular, IntPtr.Size * (Capacity - Count) )

+9
source

The capacity of the list starts from 0, if you do not specify in the constructor, and it increases when necessary (first to 4, and then always double the previous value).

  var list = new List<object>(); int capacity = list.Capacity; Console.WriteLine("Initial capacity: {0}", list.Capacity); for (int i = 0; i < 10000; i++) { list.Add(new object()); if (list.Capacity > capacity) { capacity = list.Capacity; Console.WriteLine("Capacity is {0} when count is {1}", list.Capacity, list.Count); } 
+1
source

List<T> is under the cover of the array. Its original size looks like 4 elements. When this is exceeded, the underlying array is redistributed with double size. Therefore, if you know the probable maximum size of the list, you are better off indicating it, since you will avoid the relatively expensive distribution and copying.

+1
source

If your list is less than 100,000, performance is the same in milliseconds!

But if your list is more than 1,000,000, the second way will be faster.

0
source

All Articles