Create a new list

When creating a new list, do you indicate the initial size or leave it empty? I know by specifying the initial size to avoid redistributing the base array list every time you add x number of elements, but you also add verbosity to your code. Is there a minimal increase in performance by adding verbosity and complexity to your code. What happens when this list needs another element, and you forget to add it to the initialization, which still suffers from the overhead of reallocation performance, and now the number might not make sense to new developers.

+3
source share
2 answers

If you know something about how it will be used, you should always indicate the initial size, since C # launches lists of size 4 (!) And doubles the size as the list grows. This is simply not micro-optimization, as it takes so little effort to give .Net a hint. And readability is simply not a problem, especially if you can avoid magic numbers .

+5
source

If you really cannot accurately (and easily) predict the size of the list, do not worry.

Do not create any code to determine it in advance (less code == better code).

In addition, doubling is a fairly effective way to increase the list by performance.

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

+2
source

All Articles