From cd6b189503505a5310ce87eb442d2a45f32bedb7 Mon Sep 17 00:00:00 2001 From: Mikhail Bezoyan Date: Wed, 9 Oct 2024 09:59:25 +0000 Subject: [PATCH] [util-core] Allocate a hash table of sufficient size in MapUtil.newHashMap Differential Revision: https://phabricator.twitter.biz/D1175381 --- .../main/scala-2.12-/com/twitter/util/MapUtil.scala | 11 +++++++++-- .../main/scala-2.13+/com/twitter/util/MapUtil.scala | 4 ++-- 2 files changed, 11 insertions(+), 4 deletions(-) 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) } }