1

Is it considered a best pratice to initialize Collections ( eg: Arraylist ) with initial capacity ?

From my observation through docjar, it looked like initialization reduced need for 'expansion' of initial array and also reduce the size, of internal datastructure due to resizing.

JavaDeveloper
  • 5,320
  • 16
  • 79
  • 132
  • 4
    Obviously if you know how many elements will be needed, it is a good idea. Otherwise, I just ignore it - the performance gain is negligible. – MightyPork Jul 04 '14 at 18:39

1 Answers1

0

As the comment mentions, if you know the number of elements that will be eventually needed, then it will gain you some performance since you do not have to re-allocate the backing array when the number of elements increases to exceed the current capacity.

However, there is a tradeoff because if you can't estimate it well (within an order of magnitude), then you may waste memory by allocating too much at the beginning.

merlin2011
  • 71,677
  • 44
  • 195
  • 329