Skip to content

Commit cd6b189

Browse files
mbezoyanjenkins
authored andcommitted
[util-core] Allocate a hash table of sufficient size in MapUtil.newHashMap
Differential Revision: https://phabricator.twitter.biz/D1175381
1 parent 7a99a04 commit cd6b189

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed
Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,20 @@
11
package com.twitter.util
22

3+
import java.lang.Integer.numberOfLeadingZeros
34
import scala.collection.mutable
45

56
object MapUtil {
67

7-
def newHashMap[K, V](initialCapacity: Int, loadFactor: Double = 0.75): mutable.HashMap[K, V] = {
8+
def newHashMap[K, V](expectedSize: Int, loadFactor: Double = 0.75): mutable.HashMap[K, V] = {
89
new mutable.HashMap[K, V]() {
910
this._loadFactor = (loadFactor * 1000).toInt
10-
override protected val initialSize: Int = (size.toLong / loadFactor).toInt
11+
override protected def initialSize: Int = {
12+
roundUpToNextPowerOfTwo((expectedSize / loadFactor).toInt max 4)
13+
}
1114
}
1215
}
16+
17+
private[this] def roundUpToNextPowerOfTwo(target: Int): Int = {
18+
1 << -numberOfLeadingZeros(target - 1)
19+
}
1320
}

util-core/src/main/scala-2.13+/com/twitter/util/MapUtil.scala

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import scala.collection.mutable
44

55
object MapUtil {
66

7-
def newHashMap[K, V](initialCapacity: Int, loadFactor: Double = 0.75): mutable.HashMap[K, V] = {
8-
new mutable.HashMap[K, V](initialCapacity, loadFactor)
7+
def newHashMap[K, V](expectedSize: Int, loadFactor: Double = 0.75): mutable.HashMap[K, V] = {
8+
new mutable.HashMap[K, V]((expectedSize / loadFactor).toInt, loadFactor)
99
}
1010
}

0 commit comments

Comments
 (0)