Hashmap的高性能使用小记

3 篇文章 0 订阅
1 篇文章 0 订阅
<p>An instance of <tt>HashMap</tt> has two parameters that affect its
 * performance: <i>initial capacity</i> and <i>load factor</i>.  The
 * <i>capacity</i> is the number of buckets in the hash table, and the initial
 * capacity is simply the capacity at the time the hash table is created.  The
 * <i>load factor</i> is a measure of how full the hash table is allowed to
 * get before its capacity is automatically increased.  When the number of
 * entries in the hash table exceeds the product of the load factor and the
 * current capacity, the hash table is <i>rehashed</i> (that is, internal data
 * structures are rebuilt) so that the hash table has approximately twice the
 * number of buckets.

一个HashMap的实例有两个参数会影响它的性能:初始化大小(capacity)和装载因子(load factor),由于HashMap刚开始的时候初始化capacity大小的数组,并基于链式的方式来解决Hash冲突的,load factor是衡量HashMap多满的时候增加capacity的大小(也就是增加bucket的大小),也就是说当size >(capacity * loadFactor)的时候会出现HashMap重新初始化一个新的数组,然后把原来的所有的元素重新hash到新的数组中,所以如果你使用的场景是在短时间内需要往HashMap中添加较多的元素,那么建议不要使用HashMap的默认capacity ,因为这样会引起多次的rehash(也就是ArrayList中的arrayCopy操作差不多),从而引起性能的下降,同理如果在该场景中使用ArrayList,建议根据元素的数量设置相应的大小,避免引起不必要的arrayCopy操作而降低性能

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值