在写这篇之前,默认读者已经阅读过jdk中hashMap的源码,也已大致了解其原理。最近写代码,用到存储一定数量的数据到hashMap中,优化的时候,考虑给多大的初始容量比较合适,
根据hashMap源码中:
```
/**
* Returns a power of two size for the given target capacity.
*/
final int MAXIMUM_CAPACITY = 1<<30;
static final int tableSizeFor(int cap) {
int n = cap -1;
n |= n >>>1;
n |= n >>>2;
n |= n >>>4;
n |= n >>>8;
n |= n >>>16;
return(n <0) ?1: (n >=MAXIMUM_CAPACITY) ?MAXIMUM_CAPACITY: (n +1) << 1;
}
```
没错,在此基础上,扩容一倍即可满足hashMap的最小resize值。
kotlin 代码如下:
internal val MAXIMUM_CAPACITY=1shl30
//针对给定数量cap的数据,对HashMap设置初始值,避免扩容(resize)的开销
@JvmStaticfuninitHashMapCapacity(cap: Int): Int {
var n = cap -1
n = n or n.ushr(1)
n = n or n.ushr(2)
n = n or n.ushr(4)
n = n or n.ushr(8)
n = n or n.ushr(16)
return if(n <0)1else if(n >=MAXIMUM_CAPACITY)MAXIMUM_CAPACITYelsen +1shl1
}
结束。