aspose file tools
The moose likes Java in General and the fly likes Using ensureCapacity to boost arrayList performance Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Using ensureCapacity to boost arrayList performance" Watch "Using ensureCapacity to boost arrayList performance" New topic
Author

Using ensureCapacity to boost arrayList performance

Yuma Shankar
Greenhorn

Joined: Jun 07, 2005
Posts: 24
As the default list size of an ArrayList is 10 and thereafter a copy operation is done to load additional elements in sets of 10, if we use ensureCapacity(size) for a large arraylist whose size is unknown, does the "size" parameter of ensureCapacity replace the default of 10 and causes the array to resize past the "size" specified? Hence, does that improve performance?
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 56187
    
  13

Moved to Java in General (intermediate).


[Smart Questions] [JSP FAQ] [Books by Bear] [Bear's FrontMan] [About Bear]
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18670
[Yuma]: thereafter a copy operation is done to load additional elements in sets of 10

No, ArrayList does not keep incrementing in sets of ten. Whenever it detects the need to resize its internal array, it determines the new size using the formula newCapacity = (oldCapacity * 3)/2 + 1 (you can see this in the source for JDK 1.42 - presumably other versions are similar). This results in fewer copies overall.

does the "size" parameter of ensureCapacity replace the default of 10 and causes the array to resize past the "size" specified?

No, future resizing will still follow the formula above.

Hence, does that improve performance?

You can use ensureCapacity() to improve performance, yes. If I know that a list will have at least 1000 names in it, I might presize the list to 2000 or so. That way it doesn't have to start at 10, then resize to 16, then resize to 25, then 38, 58, 88, 133, 200, 301, 452, 679, 1019, 1529...


"I'm not back." - Bill Harding, Twister
Stuart Gray
Ranch Hand

Joined: Apr 21, 2005
Posts: 410
Yes, it will surely improve performance because you are calling ensureCapacity once (to guarnatee a certain size) whereas otherwise ensureCapacity could potentially be called multiple times when adding/removing large amounts of data.
Yuma Shankar
Greenhorn

Joined: Jun 07, 2005
Posts: 24
Thanks a lot for the input.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Using ensureCapacity to boost arrayList performance
 
Similar Threads
why default size of ArrayList is 10
ensureCapacity() method in ArrayList
ArrayList ensureCapacity
Need help with ensureCapacity() function in ArrayList
ArrayList.ensureCapacity