Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Mar 8, 2011

Java Tip: Optimization Technique for Lists

The default size for a Java ArrayList class is 10. When an ArrayList reaches its capacity maximum (10), it increases its capacity by approximately half. That is why an ArrayList takes more time if it is not initialized with the proper size. When you add objects to an ArrayList and it reaches its maximum capacity, it creates another, bigger array (with a capacity of approximately 15) and copies the previous and new objects into the new array.

Obviously, creating a new array and copying objects is costly to performance. So, the best approach is to initialize the ArrayList with a proper size. To do this, you use constructors or ensureCapacity(int capacity), which results in better performance.

For example, use this code if you expect your ArrayList to store around 3000 objects:

List<String> str = new ArrayList<String>(3000)
Deepak Tyagi
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap