Which way is better for initializing a Java List:
new ArrayList<String>(futureSize)
new ArrayList<String>(futureSize + 1)
(in order to prevent resizing of the list)
futureSize
is the future size of the list once filled.
Note : If you are going to comment/answer anything about "premature optimizaton is...", "you should instead...", PLEASE DON'T. I am looking for an answer to my question, that's all.
You can see from the implementation of add(E e)
and (similar methods)
public boolean add(E e) {
ensureCapacity(size + 1);
elementData[size++] = e;
return true;
}
... that you should not run into trouble (i.e. the internal array is not resized) if you use
new ArrayList<String>(futureSize)
I'd say futureSize
is OK, although I also think that your application's performance won't depend on that optimization, unless you actually have proved with load tests and profiling that your bottleneck is array initialization.
And if you've done that, then it is much quicker to just try both variants and compare the results.
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