I did a test with both cases and the performance was irrelevant, with small values, but the memory lease is something that should be taken into account.
When you create the list with Capacity 0 (zero), o . NET will dynamically increase and allocate space as new items are added to the list, always doubling the previous capacity, i.e., in the power of 2. In practical terms, if your list has 2 elements and its capacity is 2, By adding one more element it doubles the capacity, allocating space for 4 elements. So far so good, but since it is exponential, when you have 64 elements and add one more, you will be allocated a capacity of 128, and so on. If you have 8192 elements and add another, the capacity goes to 16384 and so on.
With this we can conclude that, from the point of view of space and memory allocation, it is more advantageous to define the capacity of the list if we know the size and this is large. How big is it? You would have to analyze the type of object that goes in the list to calculate the allocated memory, but something with more than 1000 items would be interesting to define the capacity.
Here a code that demonstrates this:
System.Collections.Generic.List<int> lista = new System.Collections.Generic.List<int>();
Random rand = new Random();
int i =0;
while (i < 1000)
{
lista.Add(rand.Next(0, 20000));
i++;
Console.Write("\nTamanho: " + lista.Count.ToString());
Console.Write(" Capidade: " + lista.Capacity.ToString());
}
Can be executed here: https://dotnetfiddle.net/5Kw99i
Output example:
Size: 31 Grass: 32
Size: 32 Grass: 32
Size: 33 Grass: 64
Size: 34 Body size: 64
Note that the capacity doubles, and then the space allocated in memory also.
EDIT: I ran the same code on dotnetfiddle with 50,000, 500,000 and 1,000,000 items, without initializing the capacity and initiating. Below the results demonstrate the difference in memory consumption. Again, the performance from the time/cpu point of view was irrelevant:
+-----------+------------------+------------------+
| Itens | Sem inicializar | Inicializando |
+-----------+------------------+------------------+
| 50.000 | Memory: 512.23kb | Memory: 195.34kb |
+-----------+------------------+------------------+
| 500.000 | Memory: 4.01Mb | Memory: 1.91Mb |
+-----------+------------------+------------------+
| 1.000.000 | Memory: 8.01Mb | Memory: 3.81Mb |
+-----------+------------------+------------------+
If performance is a concern then create a List indicating your ability.
– ramaral
Is the difference significant? That’s my question, if it really makes up for.
– Thiago Loureiro
If you know the ability why not use it? You won’t have any more work if you do, so it pays off, whether it’s a significant difference or not.
– ramaral