> it would require too many re-alloc
The size uses a doubling strategy, so it won't be as bad as you think.
However, if you want to have full control, note that actually the
collection just *wraps* a list (which is created for you normally) -
you could use the alternative constructor.
The following doesn't show a huge increase for doing this... but I
guess it minimises the work of the GC and the amount of excess...
class MyCollection<T> : Collection<T> {
public MyCollection() { }
public MyCollection(int capacity) : base(new List<T>(capacity))
{ }
}
static class Program {
static void Main() {
MyCollection<int> col = new MyCollection<int>();
Fill(col, "Using default sizing");
col = new MyCollection<int>(1000000);
Fill(col, "Preallocating");
}
static void Fill(MyCollection<int> col, string message) {
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < 1000000; i++) {
col.Add(i);
}
watch.Stop();
Console.WriteLine(message);
Console.WriteLine(col.Count);
Console.WriteLine(watch.ElapsedMilliseconds);
}
}
|