返回 Skill 列表
extension
分类: 开发与工程无需 API Key

android-compose-performance

优化Android Jetpack Compose和Kotlin协程的性能。在审查、编写或重构Android Compose UI代码时,如果遇到性能问题(如重组问题、不稳定类型、懒加载布局效率低下、状态管理不当或协程误用)时使用。当用户询问关于Compose重组、状态提升、稳定性注解、调度器选择、Flow/Channel模式、协程同步或Android IPC机制(Messenger, AIDL, Binder)时也应使用。

person作者: jakexiaohubgithub

Android Compose & Kotlin Performance

Workflow

  1. Identify the problem area:

  2. Apply targeted fixes using the patterns in the relevant reference file.

  3. Verify in release mode — debug builds disable Compose compiler optimizations and skippability, making profiling unreliable.

Quick Reference: Most Common Mistakes

Compose

  • Reading state in parent when only child needs it — pass () -> T lambdas instead
  • Using List/Map/Set params (unstable) — use kotlinx.collections.immutable or @Immutable
  • Missing key in LazyColumn/LazyRow items
  • Using Modifier.offset(x, y) instead of Modifier.offset { IntOffset(x, y) } for animated values
  • Sorting/filtering inside composables instead of ViewModel
  • Profiling in debug builds

Coroutines

  • Using GlobalScope instead of viewModelScope/lifecycleScope
  • Using synchronized/ReentrantLock instead of Mutex.withLock in coroutine code
  • Collecting StateFlow without repeatOnLifecycle or collectAsStateWithLifecycle()
  • Using Channel when SharedFlow is appropriate (one-to-many) or vice versa
  • Running IO work on Dispatchers.Default or Dispatchers.Main

Recommended Architecture

  • ViewModel: MutableStateFlow for UI state, exposed as StateFlow. Logic in viewModelScope.
  • Repository/data layer: withContext(Dispatchers.IO) for disk/network. Expose Flow.
  • Compose UI: Collect via collectAsStateWithLifecycle(). Defer reads via lambdas. Use stable types. Provide keys to lazy layouts.
  • Cross-coroutine: Channel for one-to-one delivery, SharedFlow for one-to-many broadcast.
  • Synchronization: Mutex.withLock over synchronized in coroutine code.