Is it best practice to specify an initial constraint for collections?

Many collection classes in .Net (i.e. List <T>, Dictionary <TKey, TValue>) have an overloaded constructor that allows you to specify an initial capacity size. Is this constructor recommended? If so, do they have a magic number rule that you should use? That's one thing if I know the exact size ahead of time, but what if I don't?

+1


source to share


2 answers


Is it better to use this constructor?

Sure. When manipulating large amounts of data, this can make the application more efficient because it effectively prevents large data packets from being re-allocated and copied when the container is continuously filling up.

To give an example using a data structure List

:

In both cases, the insert actually has the same amortized constant lead time. This means that regardless of the size of the container, the operation Add

will take constant time. However, this is only true on average. If the container needs to be resized internally because it would otherwise overflow, this operation Add

actually takes O (n), that is, its time is proportional to the size of the container.



For many added items, this doesn't really matter, but for large n, a single insert operation might be perceived by the user if the UI freezes during that time.

This will never happen if you've already reserved a large enough capacity from the start.

If so, do they have a rule of some sort of "Magic Number" that you should use?

Not. If you know (even an approximate) size, use it. If you don't, don't worry. The auto-expanding strategy for these containers is actually pretty good, and the guesses will be much poorer in most cases (unless you have an educated guess, but then it won’t guess at all, right?).

+4


source


Since objects List<T>

grow in cardinality of 2, it is not very important to determine the initial size, unless you know that the collection will be very large. In this case, it might make sense to initialize the collection with a large size, so as not to resize it a couple of times.



Usually if I know the exact size of my collection before creating it, I just create an array and return it as IEnumerable<T>

+1


source







All Articles