Search code examples
androidappendput

Difference between put(...) and append(...) for a SparseArray?


I just want to know what is the difference between put(...) and append(...) for a SparseArray ?

From the official documentation :

  • append(...) : Puts a key/value pair into the array, optimizing for the case where the key is greater than all existing keys in the array.
  • put(...) : Adds a mapping from the specified key to the specified value, replacing the previous mapping from the specified key if there was one.

But I just do not understand :s

Thanks for your help !


Solution

  • Essentially they do the same thing. In fact the code for append uses put:

     /**
     * Puts a key/value pair into the array, optimizing for the case where
     * the key is greater than all existing keys in the array.
     */
    public void append(int key, E value) {
        if (mSize != 0 && key <= mKeys[mSize - 1]) {
            **put(key, value);**
            return;
        }
    
        if (mGarbage && mSize >= mKeys.length) {
            gc();
        }
    
        int pos = mSize;
        if (pos >= mKeys.length) {
            int n = ArrayUtils.idealIntArraySize(pos + 1);
            int[] nkeys = new int[n];
            Object[] nvalues = new Object[n];
            // Log.e("SparseArray", "grow " + mKeys.length + " to " + n);
            System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
            System.arraycopy(mValues, 0, nvalues, 0, mValues.length);
            mKeys = nkeys;
            mValues = nvalues;
        }
        mKeys[pos] = key;
        mValues[pos] = value;
        mSize = pos + 1;
    }
    

    So what is the difference? As you can see from the source code, if the key is greater than all existing keys in the array, the code will create a new size optimized array, copy all the keys/values into the new array and add the new key at the top of the array.

    When should you use it? If your keys are sequential, you get a performance advantage since you know for a fact that the next key you are going to be using is larger than the keys you used before (well, that is what sequential means:-)), so you know that you are going to need to grow the array. If your keys are not sequential, well in that case you have to "spend" the CPU power every time you add a new key to figure out if the key you are adding requires the code to grow the array or not. A large array with many keys/values and key/value inputs, that can be a bit of a performance degrader.