Efficiency and Size ArrayList

I want to clarify something: When using arraylist, it starts with a size of 10 elements. If it is necessary for automatic growth, it rewrites the entire array of List 2/3 more.

If I'm looking for a list that will eventually be 50-120 in size, is it better:

  • create it 150 in size at once and you will have a lot of unused space.
  • allow list auto-refresh multiple times?

thanks

+8
java arraylist
source share
7 answers

If you know the probable possible size of an ArrayList , it is usually best to specify it in advance:

 ArrayList myList = new ArrayList(150); 

This saves your performance impact ArrayList reallocating the array used to store its contents (although for the specified array size this effect will be negligible).

+10
source share

It's less computationally intensive to make it as large as you need right off the bat, but the truth is that java is very efficient, so there is no need to worry about how the size of the arraylist increases. However, if you intend to achieve maximum efficiency, then yes, it is better to allocate memory when creating the list.

+4
source share

Yes, it’s better to indicate the size before hand due to automatic calibration. The larger the ArrayList , the more it must resize.

+2
source share

it rewrites the entire array of List 2/3 more

Not. This makes the array twice as large (although the exact factor is the undocumented implementation detail). I stand fixed.

If I am looking for a list that will eventually be 50-120 in size, is it better to: 1. create a size of 150 immediately

Why 150? Why not 120?

  • allow list auto-refresh multiple times?

In such a small range, I would immediately use a large size. If the range was much larger (for example, 50-50000), I would reserve the smallest size (or perhaps an intermediate size, depending on the expected distribution of values) and resize it several times.

+1
source share

If you roughly know the final size, then it would be more efficient to create it with such dimensions. But for a list size of 150, it looks like micro-optimization.

+1
source share

Unless you plan on creating millions of these lists, it really doesn't matter. Copying array data is pretty fast, and increasing the size to reach 50-120 elements will not be measured using the profiler. However, if you know that the list will finally have this size, I would recommend using this information when creating the list.

+1
source share

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

Here is javadoc

Creates an ArrayList instance suitable for storing the estimated number of elements without resizing. A small number of additions are added in the case of a low rating.

+1
source share

All Articles