Skip to content

Commit 9a2f1f5

Browse files
committed
Reduce allocations within HashMap iterator for small maps
Defer allocation of the arrays used to track the cursor into the trie until iteration into the first sub-node of the root node. For tiny, shallow maps (with all data contained in the root node) or iteration that aborts early, we can save some allocation here.
1 parent 88921eb commit 9a2f1f5

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

library/src/scala/collection/immutable/ChampCommon.scala

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,14 @@ private[immutable] abstract class ChampBaseIterator[T <: Node[T]] {
8787
protected var currentValueNode: T = _
8888

8989
private[this] var currentStackLevel: Int = -1
90-
private[this] val nodeCursorsAndLengths: Array[Int] = new Array[Int](MaxDepth * 2)
91-
private[this] val nodes: Array[T] = new Array[Node[T]](MaxDepth).asInstanceOf[Array[T]]
90+
private[this] var nodeCursorsAndLengths: Array[Int] = _
91+
private[this] var nodes: Array[T] = _
92+
private def initNodes(): Unit = {
93+
if (nodeCursorsAndLengths eq null) {
94+
nodeCursorsAndLengths = new Array[Int](MaxDepth * 2)
95+
nodes = new Array[Node[T]](MaxDepth).asInstanceOf[Array[T]]
96+
}
97+
}
9298

9399
def this(rootNode: T) = {
94100
this()
@@ -103,6 +109,7 @@ private[immutable] abstract class ChampBaseIterator[T <: Node[T]] {
103109
}
104110

105111
private final def pushNode(node: T): Unit = {
112+
initNodes()
106113
currentStackLevel = currentStackLevel + 1
107114

108115
val cursorIndex = currentStackLevel * 2

0 commit comments

Comments
 (0)