Skip to content

Commit

Permalink
[util-core] Allocate a hash table of sufficient size in MapUtil.newHa…
Browse files Browse the repository at this point in the history
…shMap

Differential Revision: https://phabricator.twitter.biz/D1175381
  • Loading branch information
mbezoyan authored and jenkins committed Oct 9, 2024
1 parent 7a99a04 commit cd6b189
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
11 changes: 9 additions & 2 deletions util-core/src/main/scala-2.12-/com/twitter/util/MapUtil.scala
Original file line number Diff line number Diff line change
@@ -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)
}
}
4 changes: 2 additions & 2 deletions util-core/src/main/scala-2.13+/com/twitter/util/MapUtil.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit cd6b189

Please sign in to comment.