• Post Reply Bookmark Topic Watch Topic
  • New Topic

Using ensureCapacity to boost arrayList performance  RSS feed

 
Yuma Shankar
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moved to Java in General (intermediate).
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[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...
 
Stuart Gray
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot for the input.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!