Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best practice for setting the initial capacity of an ArrayList that is not always used?

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.

like image 247
LimaNightHawk Avatar asked Jan 21 '26 23:01

LimaNightHawk


1 Answers

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

  1. Never assume that you know what the compiled code is actually doing, or that you can sport small optimisations better than the compiler can.
  2. Never optimise without using a profiler to work out where the bottleneck is. If you think that you know, refer to rule number (1).
  3. Don't bother unless your application has a performance issue. Then refer to rule (2).

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?

like image 80
phil_20686 Avatar answered Jan 25 '26 08:01

phil_20686



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!