Are there any performance benefits if i call ArrayList.ensureCapacity() method. In what case it is advisable to make use of the method?
Are there any performance benefits if i call ArrayList.ensureCapacity() method. In what case it
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
ArrayListwith a known capacity, or in cases where the list size is unknown you should probably be considering using aLinkedListinstead.Also note that the resize strategy of
ArrayListis 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 callensureCapacityin advance you are unlikely to notice any slow-down within your code.