I want to know what is the initial size of ArrayList in C#?
-
5This may be stating the obvious, but unless you're on .NET 1.x you should really use List<T> instead.Brian Rasmussen– Brian Rasmussen2009-10-14 08:37:53 +00:00Commented Oct 14, 2009 at 8:37
-
1Your app should'n depend on that. If you know you have an upper limit of elements and performance is an issue, initialize the container with that limit, otherwise rely on its auto sizing capabilities.Frank Bollack– Frank Bollack2009-10-14 08:58:59 +00:00Commented Oct 14, 2009 at 8:58
6 Answers
0. See below.
16. (I have to add characters to this answer, since 18 characters are minimum)
Edit, Oops - the initial capacity is 16. Initial size is of course 0, because it's empty. Have to learn how to read. Or you have to learn how to form your questions. ;)
Edit again; Initial capacity of an ArrayList in .NET 1.0 is 16. In 2.0 it was 4, and now - with .NET 3.5 - the initial capacty has been lowered to 0. I don't have an explanation of why, thou.
When adding a first element to the list, the capacity will be set to 4. There after, every time when arraylist.Count eq arraylist.Capacity, the capacity will double.
4 Comments
The ArrayList starts with Size = 0 (because it's empty) and Capacity = 16.
The capacity is doubled as necessary, and capacity-doubling is a O(n) operation where n is the new capacity. So if you're inserting 5,000 elements into your list, the framework's going to be doubling the ArrayList capacity nine times - and each doubling operation is twice as expensive as the previous one.
In other words - if you know you're going to be putting 5,000 elements in a list, you're much better off explicitly initializing it to hold 5,000 elements.
You can explicitly set the Capacity of an existing arraylist if you know you're about to insert a large number of elements. You can also decrease Capacity explicitly, but if you set Capacity < Count, you'll get an ArgumentOutOfRange exception.
1 Comment
NOTE: The following seemingly only holds true for .NET 3.5; in previous versions of the framework the values were different.
According to my tests here both the initial size and capacity are zero:
PS> $a = new-object system.collections.arrayList
PS> $a.Capacity
0
PS> $a.count
0
Also, looking at the source code in Reflector, the same holds true:
public virtual int Capacity
{
get
{
return this._items.Length;
}
...
}
And _items gets set to an empty object[] in the ctor.