Which is more "expensive": creating an ArrayList that is too large or increasing the ArrayList?

I have an existing ArrayList

one that will be filtered according to certain criteria. I am using Apache CollectionUtils.select(Collection, Predicate, Collection)

for filtering.

The second collection that is passed to this method will be populated with the appropriate objects. It is now wiser to create this new collection with

List newList = new ArrayList();

      

or

List newList = new ArrayList(listToBeFiltered.size());

      

?

In the first case it List

will be increased if the initial capacity is reached, and in the second case it will sometimes be created too large List

.

Which way is better? And please correct me if I am wrong in my explanation.

+3


source to share


4 answers


This usually depends on the final size and size of the collection being collected.

Resizing ArrayList

or is usually done by doubling the current size and copying the content. Thus, with a huge final size, multiple resizing operations may be required.



On the other hand, a really large initial size can eat up quite a lot of memory and can trigger a garbage collector, but the list must be really big.

You can try and profile both, but for standard sizes I would prefer to provide a reasonable starting size.

+1


source


If you have any intuition about the selectivity of your filtering, you can increase the list to slightly larger than expected size. If the selectivity is typically 20%, then you can set the end result to (say) 25%.



 List newList = new ArrayList((int) (0.25 * listToBeFiltered.size()));

      

+1


source


In most cases, "growth" will be more expensive as it inflicts a penalty every time it needs more space. For adding a large number of records, this will result in slight run-time delays. Large selection starts with this punishment only once, unless you add more items. Note, however, that dynamic arrays / lists / containers usually have a granularity that gives reasonable capacity before they have to reallocate memory, so for a small number of items, you may not notice any difference.

0


source


Depends, you have a chance to spend some space on both.

But intuitively, if you think the resulting array will be much smaller than the input, I suggest you use List newList = new ArrayList ();

The initial capacity for an Arraylist is 10, and the size doubles if full.

0


source







All Articles