Skip to content

Commit

Permalink
Optimizes membership checking for the MacroEvaluator Session's Expans…
Browse files Browse the repository at this point in the history
…ionInfo pool.
  • Loading branch information
tgregg committed Jan 15, 2025
1 parent 9d175b3 commit cb7a07e
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions src/main/java/com/amazon/ion/impl/macro/MacroEvaluator.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import com.amazon.ion.util.unreachable
import java.io.ByteArrayOutputStream
import java.math.BigDecimal
import java.math.BigInteger
import java.util.IdentityHashMap

/**
* Evaluates an EExpression from a List of [EExpressionBodyExpression] and the [TemplateBodyExpression]s
Expand Down Expand Up @@ -53,13 +52,11 @@ class MacroEvaluator {
private var numExpandedExpressions = 0
/** Pool of [ExpansionInfo] to minimize allocation and garbage collection. */
private val expanderPool: ArrayList<ExpansionInfo> = ArrayList(32)
/** Negative view of pool so that we can have O(1) membership checks */
private val vendedExpanders: IdentityHashMap<ExpansionInfo, Unit> = IdentityHashMap(32)

/** Gets an [ExpansionInfo] from the pool (or allocates a new one if necessary), initializing it with the provided values. */
fun getExpander(expansionKind: ExpansionKind, expressions: List<Expression>, startInclusive: Int, endExclusive: Int, environment: Environment): ExpansionInfo {
val expansion = expanderPool.removeLastOrNull() ?: ExpansionInfo(this)
vendedExpanders[expansion] = Unit
expansion.isInPool = false
expansion.expansionKind = expansionKind
expansion.expressions = expressions
expansion.i = startInclusive
Expand All @@ -73,8 +70,10 @@ class MacroEvaluator {
/** Reclaims an [ExpansionInfo] to the available pool. */
fun reclaimExpander(ex: ExpansionInfo) {
// Ensure that we are not doubly-adding an ExpansionInfo instance to the pool.
check(vendedExpanders.remove(ex, Unit))
expanderPool.add(ex)
if (!ex.isInPool) {
ex.isInPool = true
expanderPool.add(ex)
}
}

fun incrementStepCounter() {
Expand Down Expand Up @@ -718,6 +717,9 @@ class MacroEvaluator {
@JvmField
var additionalState: Any? = null

@JvmField
var isInPool = false

/**
* Additional state in the form of a child [ExpansionInfo].
*/
Expand Down

0 comments on commit cb7a07e

Please sign in to comment.