Hashmap的高性能使用小記

<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操作而降低性能

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章