views:

132

answers:

2

When creating a new list do you specify an initial size or leave it blank? I know by specifying an initial size you avoid having the list reallocate the underlying array every-time you add x number of items but you also add verbosity to your code. Is the minimal performance gain worth adding verbosity and complexity to your code. What happens when that list needs one more item and you forget to add one to the initialization you still suffer from the performance overhead of reallocation and now the number may not make sense to new developers.

+5  A: 

If you know something about how it's going to be used you should always specify an initial size since C# starts lists with a size of four (!) and doubles in size as the list grows. It just isn't a micro-optimization, since it takes so little effort to give .Net the hint. And readability just isn't an issue, especially if you can avoid magic numbers.

Lee Richardson
+2  A: 

If you really can't accurately (and easily) predict the size of the list, don't bother.

Don't build any code around determining it in advance (less code == better code).

Also, doubling is a pretty effective way to grow the list with respect to performance.

4 8 16 32 64 128 256 512 1024...you get the idea.

Michael Haren