Loc Phan
Loc Phan

Reputation: 4564

Does specific type affect performance of an ArrayList?

I wonder if ArrayList<SimpleObject> and ArrayList<ComplexObject> has different performance effect if we are concerning on memory usage and navigating speed (foreach, getAt())? Why?

Thanks,

Upvotes: 0

Views: 165

Answers (3)

Vineet Reynolds
Vineet Reynolds

Reputation: 76709

Your question isn't very clear on what you are looking for, so I've made a few assumptions about what you are seeking.

If your concern is of the memory used by the list, then it will depend on the actual size of the objects being managed by the ArrayList. If SimpleObjects are lightweight compared to ComplexObjects then the memory consumed on the heap will be higher in the latter case. However, the actual memory consumed by the array lists will be more or less constant for arraylists of equal number of objects, as the lists only contain references to the actual objects on the heap.

On the topic of runtime performance, this depends on the method being invoked. Methods like get(int index) and add(E element) will always have the same runtime performance characteristics irrespective of the type being used. This is due to the nature of the method: their behavior does not depend on the type of the Object present in the list.

On the other hand, the performance of indexOf(Object object) will depend on how the equals method is implemented. For trivial cases, it would easy to infer that indexOf will run faster for ArrayList<SimpleObject> than for ArrayList<ComplexObject>, assuming that the equals() implementation of SimpleObject will run faster than that of ComplexObject.

If your concern is of memory consumption during execution of the ArrayList methods, then it is not bound to be different as most of the methods work off references of objects. There are exceptions like toArray() which would require less memory for SimpleObject than for ComplexObject.

Upvotes: 2

ngesh
ngesh

Reputation: 13501

it does make no difference, because what we store in ArrayList() is just an object reference and not the memory. so no issue what kind of class you put in to it.. so there is no performance hindrance for large class and no enhanced performance for smaller classes..

Upvotes: 1

Joachim Sauer
Joachim Sauer

Reputation: 308081

No, there is no performance difference. There are two very simple arguments to explain this:

  • An ArrayList only ever handles references and references are always the same size, no matter how complex the thing is they point to.
  • Generics are implemented using erasure, which essentially means that at runtime the information that one is an ArrayList<SimpleObject> and the other is an ArrayList<ComplexObject> is not available, they are just ArrayList objects to the runtime.

Upvotes: 2

Related Questions