Android memory optimization: ArrayMap

Source: Internet
Author: User

Android memory optimization: ArrayMap

Generally, when we use key-value to store data, we can use HashMap code at will. When the data volume is small, we can also, when the number is large, if it is on a PC, we can also say that, but if you are using a mobile device such as a mobile phone, you should be careful. Because the memory of the mobile phone is very valuable, unlike the use of the PC without any consequence, improper use of memory can easily cause OOM problems. The Android development team also found a replacement for HashMap ArrayMap.

ArrayMap is not a data structure that adapts to big data. It is slower than the traditional HashMap because the search method is a binary method and when you delete or add data, it will re-adjust the space. When using a large amount of data, the efficiency is not obvious, less than 50%.

Therefore, ArrayMap sacrifices the time-for-zone space. When writing a mobile app, using ArrayMap in a timely manner will significantly improve memory usage.

Which of the following are the differences between HashMap and ArrayMap:

1. Different storage methods.

There is a HashMapEntry in HashMap. [] Object. Each key-value pair is stored in this object. When you use the put Method to add a key-value pair, a new HashMapEntry object is created.

 

@ Override public V put (K key, V value) {if (key = null) {return putValueForNullKey (value);} int hash = secondaryHash (key); HashMapEntry
 
  
[] Tab = table; int index = hash & (tab. length-1); // first check whether the corresponding key value exists. If yes, rewrite the value and return the value before Rewriting: oldValue for (HashMapEntry
  
   
E = tab [index]; e! = Null; e = e. next) {if (e. hash = hash & key. equals (e. key) {preModify (e); V oldValue = e. value; e. value = value; return oldValue ;}// No entry for (non-null) key is present; create one modCount ++; if (size ++> threshold) {// resize, double tab = doubleCapacity (); index = hash & (tab. length-1);} addNewEntry (key, value, hash, index); return null;} // create an object storage key value pair void addNewEntry (K key, V value, int hash, int index) {table [index] = new HashMapEntry
   
    
(Key, value, hash, table [index]);}
   
  
 

There is no Entry in ArrayMap's storage. It is maintained by two arrays.

 

 

    int[] mHashes;    Object[] mArray;
The HashCode value of each item is saved in the mHashes array, and the key-value pair is in mArray. Each two elements represent one key-value pair. The key is saved before, and the value is saved later, let's take a look at the results of the following code:

 

 

arraymap = new HashMap
 
  ();a.put(a, a_value);a.put(b, b_value);
 
After the above code is executed, the storage in arraymap is like this.

 

Is it clear that the storage of ArrayMap is stored in the put Code as follows:

 

        mHashes[index] = hash;        mArray[index<<1] = key;        mArray[(index<<1)+1] = value;

2. The process for resizing when adding data is different

 

Let's take a look at HashMap.

 

        if (size++ > threshold) {            tab = doubleCapacity();            index = hash & (tab.length - 1);        }
DoubleCapacity performs double resizing, and its code contains such a sentence

 

 

HashMapEntry
 
  [] newTable = makeTable(newCapacity);
 
In the end, this newTable will be returned as a new object after resizing. What does makeTable do:

 

 

    private HashMapEntry
 
  [] makeTable(int newCapacity) {        @SuppressWarnings(unchecked) HashMapEntry
  
   [] newTable                = (HashMapEntry
   
    []) new HashMapEntry[newCapacity];        table = newTable;        threshold = (newCapacity >> 1) + (newCapacity >> 2); // 3/4 capacity        return newTable;    }
   
  
 
We can clearly see that the new operation is performed here to re-create an object, which is costly.

 

What about ArrayMap?

 

// If the capacity is insufficient, if (mSize> = mHashes. length) {final int n = mSize >=( BASE_SIZE * 2 )? (MSize + (mSize> 1): (mSize> = BASE_SIZE? (BASE_SIZE * 2): BASE_SIZE); if (DEBUG) Log. d (TAG, put: grow from + mHashes. length + to + n); final int [] ohashes = mHashes; final Object [] oarray = mArray; // assign the array allocArrays (n); if (mHashes. length> 0) {if (DEBUG) Log. d (TAG, put: copy 0-+ mSize + to 0); // pay special attention to this. It is copy, not new, which improves the efficiency of System. arraycopy (ohashes, 0, mHashes, 0, ohashes. length); System. arraycopy (oarray, 0, mArray, 0, oarray. length);} // release useless space and shrink the array freeArrays (ohashes, oarray, mSize );}


 

ArrayMap uses copy data, so the efficiency is relatively high.

 

3. ArrayMap provides the array shrinking function. After clear or remove, the array is re-scaled to determine whether the space is occupied.

4. ArrayMap uses the binary search method (see binarySearch in android. support. v4.util. ContainerHelpers)

 

 

 

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.