Skip to content

Commit 2ff728f

Browse files
committed
ListBasedPool improvement
1 parent a2e9804 commit 2ff728f

1 file changed

Lines changed: 7 additions & 1 deletion

File tree

  • fastutil4k-more-collections/src/main/kotlin

fastutil4k-more-collections/src/main/kotlin/Pool.kt

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,14 +144,18 @@ sealed interface Pool<E : Any> {
144144
// Internal storage for pooled objects
145145
private val stack = ReferenceArrayList<E>()
146146

147-
private val batchBorrowBuffer = ReferenceArrayList<E>()
147+
private var batchBorrowBuffer: ReferenceArrayList<E>? = null
148148

149149
override fun borrow(): E = if (stack.isEmpty) initializer.get() else stack.pop()
150150

151151
override fun borrowInto(
152152
destination: MutableCollection<E>,
153153
count: Int,
154154
) {
155+
fun getBuffer() = this.batchBorrowBuffer ?: ReferenceArrayList<E>().also {
156+
this.batchBorrowBuffer = it
157+
}
158+
155159
if (count < 0) throw IllegalArgumentException("count ($count) < 0")
156160
if (count == 0) return
157161

@@ -163,13 +167,15 @@ sealed interface Pool<E : Any> {
163167
0 -> return
164168
1 -> destination.add(initializer.get())
165169
else -> {
170+
val batchBorrowBuffer = getBuffer()
166171
batchBorrowBuffer.size(remaining)
167172
repeat(remaining) { batchBorrowBuffer[it] = initializer.get() }
168173
destination.addAll(batchBorrowBuffer)
169174
batchBorrowBuffer.clear()
170175
}
171176
}
172177
} else {
178+
val batchBorrowBuffer = getBuffer()
173179
batchBorrowBuffer.size(count)
174180
stack.getElements(size - count, batchBorrowBuffer.elements(), 0, count)
175181
stack.size(size - count)

0 commit comments

Comments
 (0)