Skip to content

Commit

Permalink
Fix #20521: Optimise caching for computing atoms and widened in OrTyp…
Browse files Browse the repository at this point in the history
…es (#21223)

Fix #20521

When using the `atoms` of a large provisional union type, significant
time is wasted computing the widened type and `lub` is invoked
repeatedly. This PR addresses this issue by splitting the caching
mechanisms for computing `atoms` and computing the widened type in
`OrType`.

As a result of this optimization, the compilation time for
`tests/pos/i20521.scala` has been reduced from approximately 40 seconds
to 6 seconds, making it comparable to Scala 2's performance.
  • Loading branch information
noti0na1 authored Jul 19, 2024
2 parents c734d4e + ba0d8cb commit 46867c0
Show file tree
Hide file tree
Showing 2 changed files with 805 additions and 6 deletions.
11 changes: 5 additions & 6 deletions compiler/src/dotty/tools/dotc/core/Types.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3701,6 +3701,7 @@ object Types extends TypeUtils {
myUnion

private var atomsRunId: RunId = NoRunId
private var widenedRunId: RunId = NoRunId
private var myAtoms: Atoms = uninitialized
private var myWidened: Type = uninitialized

Expand All @@ -3716,20 +3717,18 @@ object Types extends TypeUtils {
val tp2w = tp2.widenSingletons()
if ((tp1 eq tp1w) && (tp2 eq tp2w)) this else TypeComparer.lub(tp1w, tp2w, isSoft = isSoft)

private def ensureAtomsComputed()(using Context): Unit =
override def atoms(using Context): Atoms =
if atomsRunId != ctx.runId then
myAtoms = computeAtoms()
myWidened = computeWidenSingletons()
if !isProvisional then atomsRunId = ctx.runId

override def atoms(using Context): Atoms =
ensureAtomsComputed()
myAtoms

override def widenSingletons(skipSoftUnions: Boolean)(using Context): Type =
if isSoft && skipSoftUnions then this
else
ensureAtomsComputed()
if widenedRunId != ctx.runId then
myWidened = computeWidenSingletons()
if !isProvisional then widenedRunId = ctx.runId
myWidened

def derivedOrType(tp1: Type, tp2: Type, soft: Boolean = isSoft)(using Context): Type =
Expand Down
Loading

0 comments on commit 46867c0

Please sign in to comment.