Friday, 15 July 2011

java - How much should I add when resizing an array? -


I am competing with another student to make the fastest version of our homework work, and I For a demonstration reasons, ArrayList (Resizing the array, the benchmark time can be cut from 56 seconds to 4), but I am thinking that I should change the size of the array every time I need it. Particularly the relevant parts of my code are as follows:

  Private node [] list; Private integer size; // Number of items in the list Private static final end; // Each time the public MyClass () {list = How to change the size of the list by the new node [N]; } Add Public Zero (Node New Node) {If (size == list.length) {List = Arrays.copyOf (List, Size + N); } Catalog [size] = newnode; Size ++; }  

TL; DR: What should I do N ?

It is recommended to repeat the size of the array during the recycling of the linear line by doubling the size Cost increases.

The simple idea is that there are two costs associated with the value of the size:

  • Copy of the display costs - the cost of copying elements from the previous array to the new, and < / Li>
  • Memory Overhead Cost - The cost of allocated memory is not used.

If you resize the array by adding an element at a time, the memory overhead is zero, but the cost of the copy becomes quadratic if you were to allocate too many slots. The cost of copying will be linear, but memory overhead is very high.

Doubling is a linear amortized cost (i.e., for a long time, the cost of copying is linear in relation to the size of the array), and you are guaranteed that you do not waste more than half the population.

Update: Apparently Java's array list expands (3/2). It makes a bit more memory conservative, but a little higher cost in case of duplication. Your use will not harm the benchmarking.

Minimum Improvement: Resizing the doubling cost will refine the linear, but it will ensure that you have continuous continuous time insertion. Check it out.


No comments:

Post a Comment