Sameer Patil
Sameer Patil

Reputation: 536

Are there perfomance benefits with ArrayList.ensureCapacity()?

Are there any performance benefits if i call ArrayList.ensureCapacity() method. In what case it is advisable to make use of the method?

Upvotes: 4

Views: 1359

Answers (1)

Adamski
Adamski

Reputation: 54715

The performance benefit is realised in cases where you are about to add multiple elements to the list and know how many you're going to be adding. By calling ensureCapacity(int) you cause the underlying array to be resized once instead of potentially many times.

Note however, that in reality you should rarely need to call this method; typically you will either instantiate the ArrayList with a known capacity, or in cases where the list size is unknown you should probably be considering using a LinkedList instead.

Also note that the resize strategy of ArrayList is typically implemented in such a way that array copies are a rare operation (e.g. the capacity may increase by 50% every time the array becomes full). In other words, even if you do not call ensureCapacity in advance you are unlikely to notice any slow-down within your code.

Upvotes: 6

Related Questions