⚡ 重组计数与性能分析工具 Layout Inspector · Recomposition Counts · Compiler Metrics

🎯 精准定位卡顿 🧩 Jetpack Compose 专家 📊 第4章 · 实战篇

🔍 性能优化不是玄学 —— 使用 Layout Inspector 观察布局层级,借助 Recomposition Counts 发现冗余重组,通过 Compose Compiler Metrics 量化编译期稳定性。三位一体,告别卡顿。

🔎 Layout Inspector

  • 实时查看 Composable 树与布局边界
  • 测量每个节点的测量/布局耗时
  • 识别过度绘制 & 深层嵌套
  • 支持 3D 视图 & 属性面板
// 启动方式 (Android Studio)
View → Tool Windows → Layout Inspector
或直接点击右下角 Layout Inspector 标签

🔁 Recomposition Counts

  • 显示每个 Composable 的重组次数
  • 开启方式:开发者选项 → 显示更新
  • 配合 Modifier.layout 定位异常重组
  • 识别不稳定输入导致的冗余重组
// 全局开启重组计数
// 在 AndroidManifest 中:
<application
  android:debuggable="true" ...>
// 或运行时 adb shell setprop debug.compose.recomposition-counts true
📐 Compose Compiler Metrics 编译期稳定性报告

📋 关键指标

  • 稳定性 · 类/参数是否为 stable
  • 重启/跳过 · 可跳过重组次数
  • Lambda 稳定性 · 捕获参数是否稳定
  • @Stable 标记建议
// 启用 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
lambdalambda 稳定性避免捕获可变状态
knownStable已知稳定善用不可变集合
💡 示例输出片段 (ComposeCompilerMetrics):
com.example.MyComposable:
  restartable: ✅ skippable: ✅ stable: ✅
  lambda: stable (捕获参数均为稳定类型)
🔎 Layout Inspector 布局层级 · 耗时 🔄 Recomposition Counts 重组次数 · 冗余 📐 Compiler Metrics 稳定性 · 可跳过 ⚡ 性能分析铁三角 · 精准定位卡顿根源

📌 实战排查步骤

  1. 打开 Layout Inspector 检查嵌套深度
  2. 开启 Recomposition Counts 观察高频重组
  3. 分析 Compiler Metrics 报告不稳定类
  4. 使用 @Stable / immutable 修复
  5. 验证重组计数下降 & 帧率提升

🧪 代码示例:标记稳定

@Stable
data class UserProfile(
    val name: String,
    val avatarUrl: String,
    val age: Int
)

@Composable
fun ProfileCard(profile: UserProfile) {
    // 由于 UserProfile 是 stable,输入不变时重组可跳过
    Text(profile.name)
}