L
Laura T.
Jon Skeet said:Nope, it doubles the capacity each time, as Doug said. Here's code to show
that:
Yes, you are right of course. I was thinking another thing. Oh well...
happens.
Reasonable and fast, yes. A hack but reasonable one. It's still strange, andusing System;
using System.Collections.Generic;
public class ConvertFile
{
public static void Main(string[] args)
{
List<string> list = new List<string>();
int previousCapacity=-1;
for (int i=0; i < 100000; i++)
{
list.Add("");
if (list.Capacity != previousCapacity)
{
Console.WriteLine (list.Capacity);
previousCapacity = list.Capacity;
}
}
}
}
Output:
4
8
16
32
64
128
256
512
1024
2048
4096
8192
16384
32768
65536
131072
It would perhaps be nice to be able to specify the scaling factor, but 2
is reasonable for most situations.
maybe unfortunate, that the doubling behavior does not seem to be
documented.
The current wording (http://msdn2.microsoft.com/en-us/library/y52x03h2.aspx)
"If Count exceeds Capacity while adding elements, the capacity is increased
by automatically reallocating the internal array before copying the old
elements and adding the new elements." is misleading.
Still, it's not that hard to roll your own capacity calculator by deriving a
new class from List<T> and overriding the needed methods.
It's not beautiful because it needs to hide methods (new) but it can be
done. For many some applications, more linear allocation helps performance.