androidengineers.Book a session

Reflection and Runtime Features

Reflection Performance & alternatives

article15 minHard

Measure discovery separately from invocation

Reflection can cost startup time, allocation, and repeated lookup work. Cache discovered metadata when lifetimes permit, but avoid unbounded caches retaining classes or class loaders. When the model is known, explicit adapters are often simpler.

data class Lesson(val title: String, val minutes: Int)

fun Lesson.fields(): Map<String, String> = mapOf(
    "title" to title,
    "minutes" to minutes.toString()
)

This adapter is checked by the compiler and has no member-discovery phase. Generated serializers offer another option when many types need predictable adapters. Reflection remains appropriate for some plugin and inspection tools, where runtime discovery is the actual requirement.

Exercise

Compare an explicit adapter with a reflective implementation on the same data. Measure first-use discovery separately from repeated serialization, and validate identical field names and escaping before timing.

Check: a faster benchmark producing different or incomplete data is not a valid optimization. Include release-build behavior and the target platform in your assessment.

Reference: Reflection

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Reflection Performance & alternatives | Kotlin Core Programming | Android Engineers