killermist
killermist

Reputation: 27

Why does List Capacity resize to much more than is needed?

I'm trying to fill a list with 10000 random integers in the range of 0 to 20000. Here is the code for how I do it:

List<int> rand_num = new List<int>();
        Random rand = new Random();
        int i =0;
        //int counter = 0;
        while (i < 10000)
        {
            rand_num.Add(rand.Next(0, 20000));
            i++;
        }

        textBox1.Text = rand_num.Capacity.ToString();

The problem is when it gets to the textBox1.Text = rand_num.Capacity.ToString(); line, the output is 16384. I have only entered 10000 numbers, how can it re size to 6384 more than what I need? Am I missing something about how lists behave in c#?

Upvotes: 0

Views: 2379

Answers (3)

p.s.w.g
p.s.w.g

Reputation: 149010

Internally, the List<T> class stores its items in an array. Because arrays are a fixed size, adding new items is very expensive, as it requires allocating a new array and copying all the previous items into the new array. To get around this, the List<T> class grows it's array exponentially, doubling in size only once the number of items surpasses it's internal array's capacity.

In other words, Capacity doesn't refer to the number of items in the list. It refers to the number of items the list can store without having to reallocate it's internal array. Also note that you know ahead of time approximately how many items you need to store in the array, you can specify the initial capacity in the list's constructor, to avoid lots of costly reallocations (the default is 4).

Use the Count property to get the number of items in the list at any time.

Upvotes: 10

Kritner
Kritner

Reputation: 13765

You should be using:

textBox1.Text = rand_num.Count.ToString();

Upvotes: 0

Cyral
Cyral

Reputation: 14153

Capacity is how much the list can hold, before it needs to be resized internally.

Capacity is always greater than or equal to Count. If Count exceeds Capacity while adding elements, the capacity is increased by automatically reallocating the internal array before copying the old elements and adding the new elements.

What you are looking for is Count, which returns the amount of elements currently in the list.

textBox1.Text = rand_num.Count.ToString();

When the number of elements needs to become more than the capacity, .NET will resize the internal array so it can hold more values, which is generally an expensive operation. The Capacity property can also be set if you know in advance the maximum amount of values you will need.

Upvotes: 7

Related Questions