Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array vs ArrayList in performance [duplicate]

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?

like image 598
Spark-Beginner Avatar asked Oct 15 '13 19:10

Spark-Beginner


People also ask

Whose performance is better array or ArrayList?

An array is faster and that is because ArrayList uses a fixed amount of array. However when you add an element to the ArrayList and it overflows. It creates a new Array and copies every element from the old one to the new one.

Can Arraylists have duplicates?

ArrayList allows duplicate values while HashSet doesn't allow duplicates values. Ordering : ArrayList maintains the order of the object in which they are inserted while HashSet is an unordered collection and doesn't maintain any order.

Which is faster array or list in Java?

Conclusion: set operations on arrays are about 40% faster than on lists, but, as for get, each set operation takes a few nanoseconds - so for the difference to reach 1 second, one would need to set items in the list/array hundreds of millions of times!

What u think which gives best performance LinkedList and ArrayList?

Iterating through continuous memory location is more performance efficient than random memory location, that is why we prefer ArrayList over LinkedList when searching by value.


2 Answers

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.

like image 124
TwoThe Avatar answered Sep 28 '22 04:09

TwoThe


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.

like image 28
Rahul Tripathi Avatar answered Sep 28 '22 05:09

Rahul Tripathi