hashmap可以说是一个功能强大,且非常常用的工具。但是在移动平台上,google对于某些情况下并不推荐使用hashmap。正所谓魔鬼藏在细节之中,今天我们就从源码分析看看,hashmap带来的性能损耗是从哪里来的,我们又如何去避免。只有在细节处处注意性能,我们才能构建出高性能的app。
HashMap
我们首先从hashmap的put方法看起
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// 检查table大小,为空则初始化一个
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 该节点在table中的位置没有数据,直接赋值即可
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
// 冲突产生,处理冲突
Node<K,V> e; K k;
if (p.hash == hash &&