Array vs ArrayList in performance

JavaArraysPerformanceCollectionsArraylist

Java Problem Overview


Which one is better in performance between Array of type Object and ArrayList of type Object?

Assume we have a Array of Animal objects : Animal animal[] and a arraylist : ArrayList list<Animal>

Now I am doing animal[10] and list.get(10) which one should be faster and why?

Java Solutions


Solution 1 - Java

It is pretty obvious that array[10] is faster than array.get(10), as the later internally does the same call, but adds the overhead for the function call plus additional checks.

Modern JITs however will optimize this to a degree, that you rarely have to worry about this, unless you have a very performance critical application and this has been measured to be your bottleneck.

Solution 2 - Java

From here:

> ArrayList is internally backed by Array in Java, any resize operation > in ArrayList will slow down performance as it involves creating new > Array and copying content from old array to new array.


> In terms of performance Array and ArrayList provides similar > performance in terms of constant time for adding or getting element if > you know index. Though automatic resize of ArrayList may slow down > insertion a bit Both Array and ArrayList is core concept of Java and > any serious Java programmer must be familiar with these differences > between Array and ArrayList or in more general Array vs List.

Solution 3 - Java

When deciding to use Array or ArrayList, your first instinct really shouldn't be worrying about performance, though they do perform differently. You first concern should be whether or not you know the size of the Array before hand. If you don't, naturally you would go with an array list, just for functionality.

Solution 4 - Java

I agree with somebody's recently deleted post that the differences in performance are so small that, with very very few exceptions, (he got dinged for saying never) you should not make your design decision based upon that.

In your example, where the elements are Objects, the performance difference should be minimal.

If you are dealing with a large number of primitives, an array will offer significantly better performance, both in memory and time.

Solution 5 - Java

Arrays are better in performance. ArrayList provides additional functionality such as "remove" at the cost of performance.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSpark-BeginnerView Question on Stackoverflow
Solution 1 - JavaTwoTheView Answer on Stackoverflow
Solution 2 - JavaRahul TripathiView Answer on Stackoverflow
Solution 3 - JavaPaul SamsothaView Answer on Stackoverflow
Solution 4 - Javauser949300View Answer on Stackoverflow
Solution 5 - JavaAnkit RustagiView Answer on Stackoverflow