I want to know performance and efficiency of SparseArray
and ArrayList
and which one is better to use. I can't understand when to use SparseArray
and when ArrayList
?
SparseArray maps integers to Objects and, unlike a normal array of Objects, its indices can contain gaps. SparseArray is intended to be more memory-efficient than a HashMap , because it avoids auto-boxing keys and its data structure doesn't rely on an extra entry object for each mapping.
Array is a fixed length data structure whereas ArrayList is a variable length Collection class. We cannot change length of array once created in Java but ArrayList can be changed. We cannot store primitives in ArrayList, it can only store objects. But array can contain both primitives and objects in Java.
String[] is an array of Strings while ArrayList is a generic class which takes different types of objects (here it takes Strings). Therefore you can only perform normal array operations with String[].
As we all are aware of that arrays are linear data structures providing functionality to add elements in a continuous manner in memory address space whereas ArrayList is a class belonging to the Collection framework.
The purpose of a SparseArray
is to save memory if you have a list that has lots of gaps in. If you only have 10 items, and the numbers that index them range from 0 to 1000, then an ArrayList
will have lots of null
entries in it, and that will be quite wasteful. A SparseArray
will use data structures internally to avoid that problem.
The alternative in this situation is a HashMap
, which is better than a SparseArray
if you have lots of items.
The implementation is not intended to be appropriate for data structures that may contain large numbers of items. It is generally slower than a traditional HashMap, since lookups require a binary search and adds and removes require inserting and deleting entries in the array. For containers holding up to hundreds of items, the performance difference is not significant, less than 50%.
From the Android dev documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With