Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection Vs Array Performance wise

Tags:

java

Could you please let me know Performance wise why Array is better than Collection?

like image 525
Srinivasan Avatar asked Dec 17 '12 08:12

Srinivasan


People also ask

Why array is faster than collection?

An Array is a collection of similar items. Whereas ArrayList can hold item of different types. An array is faster and that is because ArrayList uses a fixed amount of array.

Why are collection objects considered more flexible than array objects?

Collections provide a more flexible way to work with groups of objects. Unlike arrays, the group of objects you work with can grow and shrink dynamically as the needs of the application change.

What is difference between collection and array?

Arrays are fixed in size, whereas some Collections are grow-able in nature. Arrays store homogeneous data. Collections store both homogeneous as well as heterogeneous data. In Arrays, there are no underlining data structures, whereas Collections have underlining data structures.

Why is ArrayList performance low?

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.


1 Answers

It is not. It will actually depend on the use you make of your container.

Some algorithms may run in O(n) on an array and in O(1) on another collection type (which implements the Collection interface).

  • Think about removal of an item for instance. In that case, the array, even if a native type, would perform slower than the linked list and its method calls (which could be inlined anyway on some VMs): it runs in O(n) VS O(1) for a linked list
  • Think about searching an element. It runs in 0(n) for an array VS O(log n) for a tree.

Some Collection implementations use an array to store their elements (ArrayList I think) so in that case performance will not be significantly different.

You should spend time on optimizing your algorithm (and make use of the various collection types available) instead of worrying of the pros/cons of an array VS Collection.

like image 140
Vincent Mimoun-Prat Avatar answered Oct 13 '22 07:10

Vincent Mimoun-Prat