diff --git a/util-core/src/main/scala-2.12-/com/twitter/util/MapUtil.scala b/util-core/src/main/scala-2.12-/com/twitter/util/MapUtil.scala index 6e180c84b..2c9bc8fd9 100644 --- a/util-core/src/main/scala-2.12-/com/twitter/util/MapUtil.scala +++ b/util-core/src/main/scala-2.12-/com/twitter/util/MapUtil.scala @@ -1,13 +1,20 @@ package com.twitter.util +import java.lang.Integer.numberOfLeadingZeros import scala.collection.mutable object MapUtil { - def newHashMap[K, V](initialCapacity: Int, loadFactor: Double = 0.75): mutable.HashMap[K, V] = { + def newHashMap[K, V](expectedSize: Int, loadFactor: Double = 0.75): mutable.HashMap[K, V] = { new mutable.HashMap[K, V]() { this._loadFactor = (loadFactor * 1000).toInt - override protected val initialSize: Int = (size.toLong / loadFactor).toInt + override protected def initialSize: Int = { + roundUpToNextPowerOfTwo((expectedSize / loadFactor).toInt max 4) + } } } + + private[this] def roundUpToNextPowerOfTwo(target: Int): Int = { + 1 << -numberOfLeadingZeros(target - 1) + } } diff --git a/util-core/src/main/scala-2.13+/com/twitter/util/MapUtil.scala b/util-core/src/main/scala-2.13+/com/twitter/util/MapUtil.scala index 2994ca876..af84a676a 100644 --- a/util-core/src/main/scala-2.13+/com/twitter/util/MapUtil.scala +++ b/util-core/src/main/scala-2.13+/com/twitter/util/MapUtil.scala @@ -4,7 +4,7 @@ import scala.collection.mutable object MapUtil { - def newHashMap[K, V](initialCapacity: Int, loadFactor: Double = 0.75): mutable.HashMap[K, V] = { - new mutable.HashMap[K, V](initialCapacity, loadFactor) + def newHashMap[K, V](expectedSize: Int, loadFactor: Double = 0.75): mutable.HashMap[K, V] = { + new mutable.HashMap[K, V]((expectedSize / loadFactor).toInt, loadFactor) } }