1.不要创建 Java 对象
在性能敏感的代码里, 尽量避免创建 Java 对象,例如:
[1] 测量 onMeasure()
[2] 布局 onLayout()
[3] 绘图 dispatchDraw(), onDraw()
[4] 事件处理 dispatchTouchEvent(), onTouchEvent()
[5] Adapter getView(), bindView()
2.GC, 垃圾回收
[1] 整个程序暂停
[2] 慢(大约几百个毫秒)
3.强行限制 (适用于调试模式)
int prevLimit = -1;
try {
prevLimit = Debug.setAllocationLimit(0);
// 执行不分配内存的代码
} catch (dalvik.system.AllocationLimitError e) {
// 如果代码分配内存, Java 虚拟机会抛出错误
Log.e(LOGTAG, e);
} finally {
Debug.setAllocationLimit(prevLimit);
}
4.管理好对象
[1] 使用软引用 内存缓存的最佳选择
[2] 使用弱引用 避免内存泄露
5.内存缓存实例
private final HashMap<String, SoftReference<T>> mCache;
public void put(String key, T value) {
mCache.put(key, new SoftReference<T>(value));
}
public T get(String key, ValueBuilder builder) {
T value = null;
SoftReferece<T> reference = mCache.get(key);
if (reference != null) {
value = reference.get();
}
if (value == null) {
value = builder.build(key);
mCache.put(key, new SoftReference<T>(value));
}
return value;
}