开发者

Java List : initial size

Which way is better for initializing a Java List:

(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.


Why not to use the apache commons FixedSizeList class

Here's the link: Apache Commons FizedSizeList


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜