Reputation: 49583
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.
Upvotes: 7
Views: 3181
Reputation: 83
new ArrayList<String>(futureSize)
Is the better way. As it is not good practice to have memory more then requirements. And about list if re-sizing is the problem, then figure out proper deviation of resizing to make it like
new ArrayList<String>(futureSize+probableDeviation)
Insertion of just 1 more element will not solve problem, so it would be better to use first one without deviation.
Upvotes: 0
Reputation: 5319
By quoting the javadoc:
ArrayList(int initialCapacity)
Constructs an empty list with the specified initial capacity.
Therefore, futureSize
should be what you use. Plain simply.
Upvotes: 2
Reputation: 5086
Why not to use the apache commons FixedSizeList class
Here's the link: Apache Commons FizedSizeList
Upvotes: 2
Reputation: 220952
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)
Upvotes: 4
Reputation: 593
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.
Upvotes: 3