一、SparseIntArray API

  SparseIntArrays map integers to integers.  Unlike a normal array of integers, there can be gaps in the indices.  It is intended to be more memory efficient than using a HashMap to map Integers to Integers, both because it avoids auto-boxing keys and values and its data structure doesn't rely on an extra entry object for each mapping.

  Note that this container keeps its mappings in an array data structure, using a binary search to find keys.  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%.

  It is possible to iterate over the items in this container using keyAt(int) andvalueAt(int). Iterating over the keys usingkeyAt(int) with ascending values of the index will return the keys in ascending order, or the values corresponding to the keys in ascending order in the case ofvalueAt(int).

SparseArray是android里为<Interger,Object>这样的Hashmap而专门写的class,目的是提高效率,其核心是折半查找函数(binarySearch)

http://developer.android.com/reference/android/util/SparseIntArray.html

二、源码

http://www.oschina.net/code/explore/android-2.2-froyo/android/util/SparseIntArray.java

/**
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package android.util; import com.android.internal.util.ArrayUtils; /***
* SparseIntArrays map integers to integers. Unlike a normal array of integers,
* there can be gaps in the indices. It is intended to be more efficient
* than using a HashMap to map Integers to Integers.
*/
public class SparseIntArray {
/***
* Creates a new SparseIntArray containing no mappings.
*/
public SparseIntArray() {
this(10);
} /***
* Creates a new SparseIntArray containing no mappings that will not
* require any additional memory allocation to store the specified
* number of mappings.
*/
public SparseIntArray(int initialCapacity) {
initialCapacity = ArrayUtils.idealIntArraySize(initialCapacity); mKeys = new int[initialCapacity];
mValues = new int[initialCapacity];
mSize = 0;
} /***
* Gets the int mapped from the specified key, or <code>0</code>
* if no such mapping has been made.
*/
public int get(int key) {
return get(key, 0);
} /***
* Gets the int mapped from the specified key, or the specified value
* if no such mapping has been made.
*/
public int get(int key, int valueIfKeyNotFound) {
int i = binarySearch(mKeys, 0, mSize, key); if (i < 0) {
return valueIfKeyNotFound;
} else {
return mValues[i];
}
} /***
* Removes the mapping from the specified key, if there was any.
*/
public void delete(int key) {
int i = binarySearch(mKeys, 0, mSize, key); if (i >= 0) {
removeAt(i);
}
} /***
* Removes the mapping at the given index.
*/
public void removeAt(int index) {
System.arraycopy(mKeys, index + 1, mKeys, index, mSize - (index + 1));
System.arraycopy(mValues, index + 1, mValues, index, mSize - (index + 1));
mSize--;
} /***
* Adds a mapping from the specified key to the specified value,
* replacing the previous mapping from the specified key if there
* was one.
*/
public void put(int key, int value) {
int i = binarySearch(mKeys, 0, mSize, key); if (i >= 0) {
mValues[i] = value;
} else {
i = ~i; if (mSize >= mKeys.length) {
int n = ArrayUtils.idealIntArraySize(mSize + 1); int[] nkeys = new int[n];
int[] nvalues = new int[n]; // Log.e("SparseIntArray", "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;
} if (mSize - i != 0) {
// Log.e("SparseIntArray", "move " + (mSize - i));
System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i);
System.arraycopy(mValues, i, mValues, i + 1, mSize - i);
} mKeys[i] = key;
mValues[i] = value;
mSize++;
}
} /***
* Returns the number of key-value mappings that this SparseIntArray
* currently stores.
*/
public int size() {
return mSize;
} /***
* Given an index in the range <code>0...size()-1</code>, returns
* the key from the <code>index</code>th key-value mapping that this
* SparseIntArray stores.
*/
public int keyAt(int index) {
return mKeys[index];
} /***
* Given an index in the range <code>0...size()-1</code>, returns
* the value from the <code>index</code>th key-value mapping that this
* SparseIntArray stores.
*/
public int valueAt(int index) {
return mValues[index];
} /***
* Returns the index for which {@link #keyAt} would return the
* specified key, or a negative number if the specified
* key is not mapped.
*/
public int indexOfKey(int key) {
return binarySearch(mKeys, 0, mSize, key);
} /***
* Returns an index for which {@link #valueAt} would return the
* specified key, or a negative number if no keys map to the
* specified value.
* Beware that this is a linear search, unlike lookups by key,
* and that multiple keys can map to the same value and this will
* find only one of them.
*/
public int indexOfValue(int value) {
for (int i = 0; i < mSize; i++)
if (mValues[i] == value)
return i; return -1;
} /***
* Removes all key-value mappings from this SparseIntArray.
*/
public void clear() {
mSize = 0;
} /***
* 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, int value) {
if (mSize != 0 && key <= mKeys[mSize - 1]) {
put(key, value);
return;
} int pos = mSize;
if (pos >= mKeys.length) {
int n = ArrayUtils.idealIntArraySize(pos + 1); int[] nkeys = new int[n];
int[] nvalues = new int[n]; // Log.e("SparseIntArray", "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;
}

本文转载自:http://blog.csdn.net/gogler/article/details/15810113

Android 开发性能优化之SparseArray(二)的更多相关文章

  1. Android 开发性能优化之SparseArray(一)

    多数Android开发者都知道在Android中可以使用HashMap来映射一种对应关系,在java开发中HashMap也算是一种很重要的数据存储结构.然后很多人在Android开发中多数都会用Has ...

  2. Android 开发性能优化之SparseArray(三)

    SparseArray是android里为<Interger,Object>这样的Hashmap而专门写的class,目的是提高效率,其核心是折半查找函数(binarySearch) pr ...

  3. Android开发性能优化总结(一)

    安卓开发应用首先要讲究良好的用户体验,如果一款软件卡顿现象严重,不流畅,经常崩溃,那么将给用户带来极不良好的体验,从而损失用户. 在实际开发和学习中,我总结了一下关于安卓性能的优化,供大家参考交流. ...

  4. (转) Android开发性能优化简介

    作者:贺小令 随着技术的发展,智能手机硬件配置越来越高,可是它和现在的PC相比,其运算能力,续航能力,存储空间等都还是受到很大的限制,同时用户对手机的体验要求远远高于PC的桌面应用程序.以上理由,足以 ...

  5. [素材资源] Android开发性能优化简介(非常不错的)

    转自(http://www.starming.com/index.php?action=plugin&v=wave&tpl=union&ac=viewgrouppost& ...

  6. Android开发性能优化大总结

    1.  采用硬件加速,在androidmanifest.xml中application添加android:hardwareAccelerated="true".不过这个需要在and ...

  7. Android开发性能优化大总结(二)

    接上篇: 1.在JAVA+Oracle 的应用系统开发中,Java中内嵌的sql语句尽量使用大写的形式,以减少Oracle解析器的解析负担: 2.由于JVM的有其自身的GC机制,但是也有遗漏的隐患,建 ...

  8. 转——Android应用开发性能优化完全分析

    [工匠若水 http://blog.csdn.net/yanbober 转载请注明出处.] 1 背景 其实有点不想写这篇文章的,但是又想写,有些矛盾.不想写的原因是随便上网一搜一堆关于性能的建议,感觉 ...

  9. Android 应用开发性能优化完全分析

    1 背景 其实有点不想写这篇文章的,但是又想写,有些矛盾.不想写的原因是随便上网一搜一堆关于性能的建议,感觉大家你一总结.我一总结的都说到了很多优化注意事项,但是看过这些文章后大多数存在一个问题就是只 ...

随机推荐

  1. SQL技巧之分组求和

    这是CSDN问答里面有人提出的一道问题,题目如下. 表格如下: 得出结果如下: 求精简的SQL语句. SQL查询语句: with a as( select rank() over (partition ...

  2. 遍历 DataSet

    DataSet ds=new DataSet ; //获取dataset的第一张table,取其他table只须改下标 DataTable dt=ds.tables[]; //遍历行 foreach( ...

  3. Sublime Text 中使用Git插件连接GitHub

    sublime Text的另一个强大之处在于它提供了非常丰富的插件,可以帮助程序员来适合大多数语言的开发.这些插件通过它自己的Package Controll(包管理)组件来安装,非常方便.一般常用的 ...

  4. iOS应用数据存储的常用方式

    iOS应用 数据存储的常用方式 XML属性列表 plist Preference 偏好设置 NSKeyedArchiver 归档 Core Data SQLite3 应用沙盒: Layer:     ...

  5. Windows phone 8 安装在 VMWare上错误的各种解决方案

    http://windowsasusual.blogspot.jp/2013/01/how-to-launch-windows-phone-8-emulator.html Hardware requi ...

  6. Delphi中的GetEnumName和GetEnumValue的使用方法

    利用TypInfo单元的GetEnumName和GetEnumValue可以遍历任意枚举类型,并获取其名称和值.下面是示例Demo. uses TypInfo; ... procedure TForm ...

  7. Python 守护进程

    import os import sys from time import sleep try: pid = os.fork() if pid > 0: sys.exit(0) # Exit p ...

  8. Hbase实例

    import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.had ...

  9. Unity3d Shader开发(三)Pass(Pass Tags,Name,BindChannels )

    Pass Tags 通过使用tags来告诉渲染引擎在什么时候该如何渲染他们所期望的效果. Syntax 语法 Tags { "TagName1" = "Value1&qu ...

  10. BZOJ 3343教主的魔法

    Description 教主最近学会了一种神奇的魔法,能够使人长高.于是他准备演示给XMYZ信息组每个英雄看.于是N个英雄们又一次聚集在了一起,这次他们排成了一列,被编号为1.2.…….N. 每个人的 ...