开发者

ArrayList Efficiency and size

开发者 https://www.devze.com 2023-03-10 20:17 出处:网络
I want to be clear on something: When using an arraylist, it starts with a size of 10 elements. If it needs to auto-increase, it rewrites the whole arrayList to be 2/3 larger.

I want to be clear on something: When using an arraylist, it starts with a size of 10 elements. If it needs to auto-increase, it rewrites the whole arrayList to be 2/3 larger.

If I'm looking 开发者_C百科at a list that will eventually be size 50-120, is it better to:

  1. create it size 150 right off and have lots of unused space
  2. allow the list to be auto-increased a few times?

Thanks


If you know the likely eventual size of the ArrayList, it's usually best to specify it upfront:

ArrayList myList = new ArrayList(150);

This saves you the performance impact of having ArrayList re-allocate the array used to store its content (although, for the array size that you've specified, this impact will be negligible).


It is less computationally intensive to make it about as large as you will need right off the bat, but the truth is that java is very efficient, so it really isn't necessary to worry about how the arraylist is increased. However, if you are going for maximum efficiency, then yes, allocating the memory when you create the list is better.


it rewrites the whole arrayList to be 2/3 larger

No. It makes the array twice as large (although the exact factor is an undocumented implementation detail). I stand corrected.

If I'm looking at a list that will eventually be size 50-120, is it better to: 1. create it size 150 right off

Why 150? Why not 120?

  1. allow the list to be auto-increased a few times?

In such a small range I would use the large size right away. If the span was much larger (e.g. 50–50000) I would reserve the smallest size (or perhaps an intermediate size, depending on the expected value distribution) and let it resize a few times.


Yes, Specifying the size before hand is better, because of auto-sizing. The bigger the ArrayList gets the more it has to resize itself.


If you roughly know the final size, then it would be more efficient to create it at that size. But for a list size of 150, this seems like a micro-optimization.


As long as you do not plan to create millions of these lists, it doen't actually matter. Copying array data is pretty fast and increasing the size to reach 50-120 items will not be measureable with a profiler. However, if you know that the list will finally have this size, I'd recommend to use this information when creating the list.


You can also use nice method from Guava Lists.newArrayListWithExpectedSize.

Here is the javadoc

Creates an ArrayList instance sized appropriately to hold an estimated number of elements without resizing. A small amount of padding is added in case the estimate is low.

0

精彩评论

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