Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Generic List with default size or supply one

Tags:

c#

generics

I am wondering if there is difference (in the aspect of performance, memory saving) to define a list with a default size or specify one.

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

or 

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

Both will increase the size by doubling up if more items are added, right?

Thanks,

like image 411
Icerman Avatar asked Dec 28 '22 14:12

Icerman


1 Answers

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

Every time it "doubles up", it needs to copy the contents of the entire existing array. For large lists, this can be slow.
If you specify the capacity, it won't need to resize at all until it gets bigger than what you specified.

If you never add more than 100 items, it justs wastes a bit of memory (specifically, IntPtr.Size * (Capacity - Count))

like image 154
SLaks Avatar answered Jan 13 '23 05:01

SLaks