Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a new List

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.

like image 913
joegtp Avatar asked Apr 06 '26 16:04

joegtp


1 Answers

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.

like image 77
Lee Richardson Avatar answered Apr 09 '26 04:04

Lee Richardson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!