Android app performance optimization using Sparsearray instead of HashMap

Source: Internet
Author: User

An overview of recent projects in the Sparsearray, curious study under. Sparsearray is a class unique to the Android framework and does not exist in the standard JDK. It saves memory more than HASHMAP, and in some cases is better than HashMap, as explained by the official answer, mainly because Sparsearray does not need to auto-boxing the key and value (the original type is encapsulated as an object type, For example, the int type is encapsulated as an integer type, and the structure is simpler than HashMap (Sparsearray internally uses two one-dimensional arrays to hold the data, one to store the key, An additional data structure (primarily for hashmapentry in HashMap) is not required to store value.
Second, the explanation is purely literal understanding, sparsearray refers to the sparse array (Sparse array), the so-called sparse array is the array of most of the content values are not used (or all 0), in the array only a small portion of the space used. Therefore, the memory space wasted, in order to save memory space, and do not affect the contents of the array of content values, we can use a compressed way to represent the contents of the sparse array.

Suppose there is an array of 9*7, with the following contents:

In this array, there are 63 spaces, but only 5 elements are used, resulting in a waste of 58 element space. Let's use the sparse array to redefine the array:
Where the first part of the sparse array records the number of columns and rows of the original array and the number of elements used, the second part records the position and contents of the elements in the original array. After compression, the original need to declare an array of size 63, and after using compression, only need to declare an array of size 6*3, only 18 storage space.
Light said no Ah, can not you say performance good performance, is the Mule is horse-drawn out to sneak, we write two paragraph test program: Code 1:
int MAX = 100000;long start = System.currenttimemillis (); Hashmap<integer, string> hash = new Hashmap<integer, string> (); for (int i = 0; i < MAX; i++) {    hash.put (I, string.valueof (i));} Long ts = System.currenttimemillis ()-Start;
Code Listing 2:
int MAX = 100000;long start = System.currenttimemillis (); Sparsearray<string> sparse = new sparsearray<string> (); for (int i = 0; i < MAX; i++) {    sparse.put (i, St Ring.valueof (i));} Long ts = System.currenttimemillis ()-Start;
In the above two pieces of code, we use HashMap and Spasearray, respectively, to insert 100,000 data, the data is as follows:
# Code 1 Code 2    
Time 10750ms 7429ms
Space 13.2M 8.26M
The visible use of Sparsearray is indeed more memory-saving than HashMap, saving about 35% or so.
And in the positive order condition, the time is about 33% faster than the HashMap.
We turn the positive order into reverse order Code 3:
int MAX = 100000;long start = System.currenttimemillis (); Hashmap<integer, string> hash = new Hashmap<integer, string> (); for (int i = 0; i < MAX; i++) {    hash.put (Max-i-1, string.valueof (i));} Long ts = System.currenttimemillis ()-Start;
Code Listing 4:
int MAX = 100000;long start = System.currenttimemillis ();  Sparsearray<string> sparse = new sparsearray<string> (); for (int i = 0; i < max; i++) {    sparse.put (max- I-1, string.valueof (i));} Long ts = System.currenttimemillis ()-Start;

The results of the operation are as follows:
# Code 1 Code 2 Code 3 Code 4
1 10750ms 7429ms 10862ms 90527ms
2 10718ms 7386ms 10711ms 87990ms
3 10816ms 7462ms 11033ms 88259ms
4 10943ms 7386ms 10854ms 88474ms

By the result we can see that the Sparsearray is faster than hashmap when inserting the data in the positive order; The HashMap is almost the same either in reverse or in the positive order, but the reverse insertion of sparsearray is 10 times times slower than the positive order insertion. Follow the source code and find the Put method:
public void put (int key, E value) {        int i = BinarySearch (Mkeys, 0, msize, key);        if (I >= 0) {            mvalues[i] = value;        } else {            i = ~i;            if (i < msize && mvalues[i] = = DELETED) {                mkeys[i] = key;                Mvalues[i] = value;                return;            }            if (mgarbage && msize >= mkeys.length) {                gc ();                Search again because indices may have changed.                i = ~binarysearch (Mkeys, 0, msize, key);            }            ............

Before you put the data, you will find out whether the data you want to put already exists, and if so, add it if it exists. There is a search process, that is binarysearch, what a ghost ah, and go to see:
private static int BinarySearch (int[] A, int start, int len, int key) {        Int. = start + len, low = start-1, guess ;        while (High-Low > 1) {            guess = (high + low)/2;            if (A[guess] < key) low                = guess;            else high                = guess;        }        if (high = = start + len)            return ~ (start + len);        else if (a[high] = = key)            return high;        else            return ~high;    }

Soga, it turns out to be a binary search. Then the reason is found, it is because sparsearray in the retrieval of data using a binary search, so each time you insert new data sparsearray need to reorder, so in code 4, reverse is the worst case.
In addition, the performance of Sparsearray is notch above when there are subscripts in Sparsearray that need to be retrieved. But when the index of the search is discrete, Sparsearray needs to use multiple binary search, performance is slower than hash retrieval, but according to official documents, performance difference is not very large, not more than 50% (for containers holding Hundreds of items, the performance difference is not significant, less than 50%.)
Third, summarize overall, in the Android This memory is more Jin GUI than CPU system, can use memory economically or the best policy, and Sparsearray in other aspects of performance is not bad (in addition, Sparsearray delete the data is also optimized- Using the method of deferred sorting arrays, refer to the official documentation

Summary: Sparsearray is a class specifically written for <Interger,Object> such hashmap in Android, designed to improve efficiency, with the core of binary lookup function (binarysearch). In Android, when we need to define
Hashmap<integer, e> HashMap = new Hashmap<integer, e> ();
, we can use the following methods to achieve better performance.
sparsearray<e> Sparsearray = new sparsearray<e> ();

Reference:
    • Sparsearray
    • Two-point Search
    • Sparse matrices


Android app performance optimization using Sparsearray instead of HashMap

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.