KansaiRobot
KansaiRobot

Reputation: 9982

Is it worth to resize a List in C#?

I am intending to use a List in my C# program. Now, everytime I call a function makeTemplate the contents as well as the size of the list will change. I was thinking of resizing the list (haven't thought of how to do this yet, I heard AddRange might be ok for this) but then I thought, why not just create another list, abandon the previous one and let the GC deal with that. Something along these lines

class aClass
{
   private List<float> template;

   public ivoid makeTemplate(size)
   {
      //Here I abandon the previous template hold in some memory and 
      //get some new list
     template= new List<float>(size);
     //.....
   }

}

I am thinking it is better this way, Any opinion on this? (I imagine that in C++ I will have to check if it is null and delete the memory before doing this)

Upvotes: 1

Views: 346

Answers (1)

piojo
piojo

Reputation: 6723

The list will resize its buffer automatically, so there's no point in creating a new list and throwing away the old one. You can set the list capacity if you know the final size in advance--this will save memory by making the buffer only as big as you need. It will also save CPU time if the increase in size is so dramatic that it involves multiple resize/copy operations--your code will only need one operation.

The C# List class works almost the same as a C++ vector, if you're more familiar with C++. In each, the buffer is doubled each time it increases.

AddRange automatically increases the list size to the right number, instead of potentially increasing more than once during your addition of elements as it would do if you add one-by-one.

So in short, don't worry about it, use AddRange if it's equally convenient, and set the list capacity if you know it in advance.

If you want to see the C# source, these are the most important classes for analyzing the performance of containers: Enumerable, List.

Upvotes: 4

Related Questions