Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java List : initial size

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.

like image 773
Matthieu Napoli Avatar asked Jun 10 '11 09:06

Matthieu Napoli


2 Answers

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)
like image 189
Lukas Eder Avatar answered Oct 02 '22 23:10

Lukas Eder


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.

like image 41
deltaforce2 Avatar answered Oct 02 '22 22:10

deltaforce2