Skip to content

[KSP2][Performance]: Memoize KSTypeImpl.fullyExpand() or KSTypeImpl.hashCode()? #2576

@bcorso

Description

@bcorso

In Dagger we found a particularly slow part of our build was creating our KspArrayType$Factory

Image

The pprof above shows that this issue is due to creating the reverseBuiltInArrayLookup map (shown below for convience):

private val builtInArrays =
    mapOf(
        "kotlin.BooleanArray" to KspPrimitiveType(env, env.resolver.builtIns.booleanType),
        "kotlin.ByteArray" to KspPrimitiveType(env, env.resolver.builtIns.byteType),
        "kotlin.CharArray" to KspPrimitiveType(env, env.resolver.builtIns.charType),
        "kotlin.DoubleArray" to KspPrimitiveType(env, env.resolver.builtIns.doubleType),
        "kotlin.FloatArray" to KspPrimitiveType(env, env.resolver.builtIns.floatType),
        "kotlin.IntArray" to KspPrimitiveType(env, env.resolver.builtIns.intType),
        "kotlin.LongArray" to KspPrimitiveType(env, env.resolver.builtIns.longType),
        "kotlin.ShortArray" to KspPrimitiveType(env, env.resolver.builtIns.shortType),
    )

// map from the primitive to its array
private val reverseBuiltInArrayLookup =
    builtInArrays.entries.associateBy { it.value.ksType }

While we ended up fixing this performance issue by caching the factory instance (which removes nearly the entire 63s), it also would have helped to have more caching at the KSP level.

For example, given that the majority of time is spent calculating hashcodes for the same 8 builtin types above, memoizing the result of KSTypeImpl.hashcode() or KSTypeImpl.fullyExpand() would have helped here, assuming these types are indeed immutable (i.e. there hashes don't change over time).

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2affects usability but not blocks users
    No fields configured for Feature.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions