Optimizing Android App With ArrayMap&SparseArray
Optimizing Android App With ArrayMap&SparseArray
AndroidPub
Collections are the most common thing used in the software development. In general
whenever we required to store data in key value pairs, the very first data structure that
comes to our mind is HashMap. It is quite flexible hence it is the most preferred data
structure choice to store key value pairs.
When a key-value pair is inserted into a HashMap, a hashCode of the key is calculated,
and that value is assigned to the hashCode variable of EntryClass. Now using
hashCode, we can get the index of the bucket where it will be stored. In case bucket
has a pre-existing element, the new element is inserted with the last element pointing to
new one essentially making the bucket a linked list.
It has a constant time, or O(1) time requirement for retrieving an element from the array.
This means that it takes the same time to pull any element from the array, regardless of
the size. This is possible by using a hashing function, which generates the array
indices, given the input key.
Below are the example code to create HashMap and fetch keys and values:
Below are the example code to create ArrayMap and fetch keys and values:
Class appear even in the API 1, but has been redesigned in the API 11. The updated
version SparseArrayCompat also available for older devices in the compatibility library.
Comparison
Continuous allocation and de-allocation of memory along with garbage collection will
cause lag in Android application and it reduces the application performance. Other than
this ArrayMap & SparseArray avoid memory problem by using 2 small arrays rather
than one big one.
· No auto-boxing
· Allocation-free
Drawbacks:
In general if inserts or deletes are fairly infrequent, and the number of items is < 1000
then ArrayMap / SparseArray classes are really good replacement classes.
This video from Android developers will provide you further details.
Conclusion
As we can conclude that the SparseArray is a more efficient solution than using a
Hashmap to map Integers to objects. The theory is that the SparseArray can add and
retrieve elements quicker than a HashMap (<1000), in this case, by removing the
hashing function processing time.
Thanks for reading. To help others please click ❤ to recommend this article if you found
it helpful.
Check out my blogger page for more interesting topics on Software development.
672
5
claps
AndroidPub Follow
The Pub(lication) for Android & Tech, focused on
Development