ArrayList after TrimToSize() capacity is always 4 why ?

R

raagzcd

Hi,

In the following sample code.

ArrayList arrlist = new ArrayList(3);
int count = arrlist.Count;
int cpty = arrlist.Capacity;
arrlist.TrimToSize();
int newctpy = arrlist.Capacity;

cpty value is : 3
newctpy value is : 4

why is the new capacty value after TrimToSize() on the arraylist is 4 ?

even if arraylist size is changed to 2 newctyp value still remains as 4
!

Can anybody explain me more about this ?

Regards
Raagz
 
G

Greg Young

A quick look with reflector will reveal the following code in the ArrayList
class. In the case that 0 is passed through such as in your example, an
array of initial size 4 is created. I would imagine this has been done based
upon some usage metrics and has shown to be more efficient in the long run.
I would imagine this is done to avoid the copy / grows for the small
doublings ...

Cheers,

Greg Young
MVP - C#

public virtual int Capacity
{
get
{
return this._items.Length;
}
set
{
if (value != this._items.Length)
{
if (value < this._size)
{
throw new ArgumentOutOfRangeException("value",
Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
}
if (value > 0)
{
object[] objArray1 = new object[value];
if (this._size > 0)
{
Array.Copy(this._items, 0, objArray1, 0,
this._size);
}
this._items = objArray1;
}
else
{
this._items = new object[4];
}
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top