I have some classes that have ArrayList fields that are only sometimes used. I generally initialize these fields like so:
private List<Widget> widgets = new ArrayList<>();
I understand about using the overload constructors to set the initial capacity, so I'm wondering if I should declare these fields as such:
private List<Widget> widgets = new ArrayList<>(0);
The dilemma, is that if I initialize the list with 0 then the list will always have to re-initialize itself for adding even one item. But, if I use the default constructor, which gives a default capacity of 10, then I may have a bunch of items (and there can be many) that are wasting memory with unused capacity.
I know some of you are going to push back asking 'how often' and 'how many items are you expecting' but I'm really looking for the "best practices" approach. All things being ~equal, should one initialize with (0) or () on a list that is sometimes used?
It's our department policy to always initialize lists, so I may not simply leave the lists as null, besides, that would just side-step the question.
Premature optimisation is the root of all evil. - D. Knuth.
This seems like the kind of "performance issue" which actually never has any effect on performance. For one thing, how sure are you that these empty lists are actually initialised? I suspect that most modern compilers delay initialisation of objects until they know for sure that there will be a call on them. So if you pass the no arg constructor it will most likely never be used unless something is added to the list. On the other hand, if you use the 0 argument constructor, it guarantees that it has to resize every one that it uses.
These are the three laws of performance optimisation
On the off chance that you somehow still believe that you understand compilers, check out this question: Why is it faster to process a sorted array than an unsorted array?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With