Otis wrote:
Capacity is always >= the count, as capacity is increased as soon as internally the storage of the data has to be increased.
Thats right but what the code is doing is adding the new count to the existing capacity so the capacity will always increase.
Actually, I think it should be
_contents.Capacity = Math.Max(_contents.Capacity, _contents.Count + c.Count);
(I mixed up Capacity with EnsureCapacity which doesn't reduce, only increases)
By adding the new count the existing count, you will only increase the capacity when actually necessary.
[Test]
public void TestEmptyCollectionCapacity()
{
EntityCollection<VoyageEntity> data = new EntityCollection<VoyageEntity>();
Console.WriteLine(data.Capacity);
data.Add(new VoyageEntity());
Console.WriteLine(data.Capacity);
}
[Test]
public void TestEmptyCollectionCapacityRange()
{
EntityCollection<VoyageEntity> data = new EntityCollection<VoyageEntity>();
Console.WriteLine(data.Capacity);
data.AddRange(new VoyageEntity[] {new VoyageEntity()});
Console.WriteLine(data.Capacity);
}
The former, does not increase the Capacity - it stays at 256
The latter's Capacity is 257. If you add 1000 entities it would be 1256.
Incidentally, InitClassCore() is called with an initial capacity of 32 or 256 depending on how it is created. I think that 256 is way too much taking up 1KB even for an empty array.
List<T> uses 4 as a default and then doubles in size - I've tried various options for presizing collections in my serialization stuff and I've not yet been able to find a worthwhile reason unless the size is actually known- in fact time often increased because of additional GCs - the internal resizing is extremely quick.
Cheers
Simon