tags:

views:

149

answers:

8

What is the best practice to initialize an ArrayList in Java?

If I initialize a ArrayList using new operator then, the ArrayList will by default have memory allocated for the 10 buckets (say the object) by default. Which is a performance hit.

I don't know, might be I am wrong, but it seems to me that I must create a ArrayList by mentioning the size, if I am sure about the size.!!!

+4  A: 

Which is a performance hit.

I wouldn't worry about the "performance hit". Object creation in Java is very fast. The performance difference is unlikely to be measurable by you.

By all means use a size if you know it. If you don't, there's nothing to be done about it anyway.

The kind of thinking that you're doing here is called "premature optimization". Donald Knuth says it's the root of all evil.

A better approach is to make your code work before you make it fast. Optimize with data in hand that tells you where your code is slow. Don't guess - you're likely to be wrong. You'll find that you rarely know where the bottlenecks are.

duffymo
Yeah, I agree..right now We are working on performance issues..As everything is working fine as of now according to the requirement. So, we are just bothered about the performance.I understand that the object creation in Java is very fast, but still they require some time. If the number of such ArrayList is large, then the time is noticeable too..!!There are other ways to improve the optimization, but is this could be a way??
Pradeep
As I know that I always have a single object in the ArrayList which I had initialized, then is it correct way of initializing the ArrayList with 10 buckets, out of which 9 will always remain empty.
Pradeep
If you ALWAYS have a single object in a List, I'd question why you've designed a class that uses a List. Why not a reference to the single object? And if you tell me "I MIGHT have more than one...", then your ALWAYS statement is incorrect.
duffymo
Too many "ifs". First you only have one object, then it might be large. Which one is it? Sounds like a lot of confused hypotheticals. Do you have profiling data that says this list is the downfall of your app? If not, you're wasting your time.
duffymo
I have a common method which will return me the List.But from my module when I will call that method, that will return a single object. So, I had to create a List.
Pradeep
No I am not saying this that "this list is the downfall of your app" Just trying to figure out is this could be the one? My algorithm is running quite fast..I dunno how fast it could be. If there is any possibility, if no, then its fine
Pradeep
You're wasting your time and ours.
duffymo
@Pradeep: if you're unsure where the app is spending its time, then this kind of guessing game is useless if not counterproductive. Use a profiler!!!
Michael Borgwardt
:) Thanks :-)I got the idea how to work around this.
Pradeep
+1  A: 

If you already know the size of your ArrayList (approximately) you should use the constructor with capacity. But most of the time developers don't really know what will be in the List, so with a capacity of 10 it should be sufficient for most of the cases.

10 buckets is an approximation and isn't a performance hit unless you already know that your ArrayList contains tons of elements, in this case, the need to resize your array all the time will be the performance hit.

Colin Hebert
+3  A: 

If you know how many elements you will add, initialize the ArrayList with correct number of objects. If you don't, don't worry about it. The performance difference is probably insignificant.

Carlos
A: 

Since ArrayList is implemented by array underlying, we have to choose a initial size for the array.

卢声远 Shengyuan Lu
A: 

If you really care you can call trimToSize() once you have constructed and populated the object. The javadoc states that the capacity will be at least as large as the list size. As previously stated, its unlikely you will find that the memory allocated to an ArrayList is a performance bottlekneck, and if it were, I would recommend you use an array instead.

Jon Freedman
+3  A: 

This is the best advice I can give you:

  • Don't worry about it. Yes, you have several options to create an ArrayList, but using the new, the default option provided by the library, isn't a BAD choice, otherwise it'd be stupid to make it the default choice for everyone without clarifying what's better.
  • If it turns out that this is a problem, you'll quickly discover it when you profile. That's the proper place to find problems, when you profile your application for performance/memory problems. When you first write the code, you don't worry about this stuff -- that's premature optimization -- you just worry about writing good, clean code, with good design.
  • If your design is good, you should be able to fix this problem in no time, with little impact to the rest of the system. Effective Java 2nd Edition, Item 52: Refer to objects by their interfaces. You may even be able to switch to a LinkedList, or any other kind of List out there, if that turns out to be a better data structure. Design for this kinds of flexibility.
  • Finally, Effective Java 2nd Edition, Item 1: Consider static factory methods instead of constructors. You may even be able to combine this with Item 5: Avoid creating unnecessary objects, if in fact no new instances are actually needed (e.g. Integer.valueOf doesn't always create a new instance).

Related questions


On ArrayList micromanagement

Here are some specific tips if you need to micromanage an ArrayList:

  • You can use ArrayList(int initialCapacity) to set the initial capacity of a list. The list will automatically grow beyond this capacity if needed.
  • When you're about to populate/add to an ArrayList, and you know what the total number of elements will be, you can use ensureCapacity(int minCapacity) (or the constructor above directly) to reduce the number of intermediate growth. Each add will run in amortized constant time regardless of whether or not you do this (as guaranteed in the API), so this can only reduce the cost by a constant factor.
  • You can trimToSize() to minimize the storage usage.

This kind of micromanagement is generally unnecessary, but should you decide (justified by conclusive profiling results) that it's worth the hassle, you may choose to do so.

See also

polygenelubricants
+1  A: 

You don't need to tell initial size of ArrayList. You can always add/remove any element from it easily.

If this is a performance matter, please keep in mind following things :

  1. Initialization of ArrayList is very fast. Don't worry about it.
  2. Adding/removing element from ArrayList is also very fast. Don't worry about it.
  3. If you find your code runs too slow. The first to blame is your algorithm, no offense. Machine specs, OS and Language indeed participate too. But their participation is considered insignificant compared to your algorithm participation.
jancrot
+1  A: 

If you don't know the size of theArrayList, then you're probably better off using a LinkedList, since the LinkedList.add() operation is constant speed.

However as most people here have said you should not worry about speed before you do some kind of profiling.

You can use this old, but good (in my opinion) article for reference. http://chaoticjava.com/posts/linkedlist-vs-arraylist/

Simeon