Using ensureCapacity to boost arrayList performance
Joined: Jun 07, 2005
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?
[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
Joined: Apr 21, 2005
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.