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.
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.
source to share
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()));
source to share
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.
source to share