views:

72

answers:

4

When I learned Java, I was told that the arraylist works this way:

  • It creates an array with room for 10 elements.

  • When the 11th element is added, it is created a new list with room for 20 elements, and the 10 elements are copied into the new array. This will repeat as until there are no more elements to add, or to a maximum size.

Is the List in .NET constructed the same way?

+1  A: 

The generic List type doubles its internal array length every time the current array is filled up.

MSDN Link

Dario Solera
+3  A: 

You can easily test this by querying a List's Capacity:

    var a = new List<string>();

    Console.WriteLine(a.Capacity); // Writes 0

    a.Add("abc");

    Console.WriteLine(a.Capacity); // Writes 4

    a.Add("abc");
    a.Add("abc");
    a.Add("abc");
    a.Add("abc");

    Console.WriteLine(a.Capacity); // Writes 8

So it doesn't allocate any room at all upon instantiation, but upon first added item. From 8 it grows to 16, 32, etc...

David Hedlund
+1 for giving a demonstrated answer, and a personal "hurrah" for anyone who knocks up a few lines of code to prove a theory :-)
Dan Puzey
@Dan: It's hardly an effort, once you've got Snippet Compiler: http://www.sliver.com/dotnet/SnippetCompiler/
David Hedlund
I use Linqpad for the same thing all the time. But you're still one of a rare breed around StackOverflow ;-)
Dan Puzey
I never tried Snippet Compiler actually - do you have to declare the class/namespace each time?
Dan Puzey
nah, it sets you up with a little stub on startup, so the only code I actually wrote, was the stuff that I ended up pasting to SO.
David Hedlund
Unless this specific behaviour is mandated by the framework documentation (I haven't checked), it's very dangerous to rely on an observed behaviour, if it is actually required. Even if you get the output 0, 4 and 8 with your .NET version, other versions or other implementations of the framework (e.g. Mono) may give a different output.
jarnbjo
@jarnbjo: granted, but my code was arguably just a means of showing off how to use `Capacity`. My initial reply was "You can easily test this by querying a List's Capacity", and if we are to make allowance for the fact that the observed behavior may differ depending on environmental variables, then checking for yourself is pretty much the *only* way of reliably finding out how ones own deployment behaves, and my answer taught how to do that.
David Hedlund
+1  A: 

The details are a bit different (in terms of the default number of elements and how it expands), but essentially it is the same.

Oded
+1  A: 

I believe that's how it works, yes. I can't find any documentation at the moment that tells you the exact algorithm they use, but there is definitely the concept of Capacity (size of the "internal" array) and Count (the actual number of elements you've added).

Dean Harding