Skip to content

Commit

Permalink
InternMap: improve initial capacity calculation
Browse files Browse the repository at this point in the history
A value that ensures no re-hash is maxCapacity / 0.75 + 1, we use that value / 2 as initial capacity
  • Loading branch information
handymenny committed Aug 2, 2024
1 parent 7a17729 commit a3cec4c
Showing 1 changed file with 11 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ open class InternMap<T>(maxCapacity: Int) {
@Transient private val lock = Any()

private val internalMap: LinkedHashMap<T, T> =
object : LinkedHashMap<T, T>(minOf(16, maxCapacity), 0.75f) {
object : LinkedHashMap<T, T>(computeInitialCapacity(maxCapacity)) {
override fun removeEldestEntry(eldest: Map.Entry<T, T>): Boolean {
return size > maxCapacity
}
Expand All @@ -23,6 +23,16 @@ open class InternMap<T>(maxCapacity: Int) {
}

fun intern(value: T): T = internalMap[value] ?: put(value)

companion object {
private fun computeInitialCapacity(maxCapacity: Int): Int {
// A value that ensures no re-hash is maxCapacity / 0.75 + 1
// Compute that value / 2
val initialCapacity = Math.floorDiv(maxCapacity * 2, 3) + 1

return maxOf(16, initialCapacity)
}
}
}

object MimoInternMap : InternMap<Mimo>(100)
Expand Down

0 comments on commit a3cec4c

Please sign in to comment.