🔍 性能优化不是玄学 —— 使用 Layout Inspector 观察布局层级,借助 Recomposition Counts 发现冗余重组,通过 Compose Compiler Metrics 量化编译期稳定性。三位一体,告别卡顿。
// 启动方式 (Android Studio) View → Tool Windows → Layout Inspector 或直接点击右下角 Layout Inspector 标签
Modifier.layout 定位异常重组// 全局开启重组计数 // 在 AndroidManifest 中: <application android:debuggable="true" ...> // 或运行时 adb shell setprop debug.compose.recomposition-counts true
// 启用 Compiler Metrics (build.gradle)
composeOptions {
kotlinCompilerExtensionVersion = "1.5.10"
}
// 添加编译参数
kotlinOptions {
freeCompilerArgs += [
"-P",
"plugin:androidx.compose.compiler.plugins.kotlin:metricsDestination=" +
project.buildDir.absolutePath + "/compose-metrics"
]
}
| 指标 | 说明 | 优化方向 |
|---|---|---|
| restartable | 可重启重组 | 减少不稳定参数 |
| skippable | 可跳过重组 | ✅ 理想状态 |
| stable | 参数/类稳定 | 使用 immutable / @Stable |
| lambda | lambda 稳定性 | 避免捕获可变状态 |
| knownStable | 已知稳定 | 善用不可变集合 |
com.example.MyComposable: restartable: ✅ skippable: ✅ stable: ✅ lambda: stable (捕获参数均为稳定类型)
@Stable / immutable 修复@Stable
data class UserProfile(
val name: String,
val avatarUrl: String,
val age: Int
)
@Composable
fun ProfileCard(profile: UserProfile) {
// 由于 UserProfile 是 stable,输入不变时重组可跳过
Text(profile.name)
}