Android Performance: Những thứ thật sự làm app chậm (và cách xử lý thực tế)
Source: Dev.to
Hiểu đúng về “Android Performance”
Rất nhiều bài viết nói về performance theo kiểu:
- tránh object allocation
- optimize code nhỏ lẻ
👉 Nhưng trong app thật, 80 % vấn đề performance đến từ:
- Main Thread bị block
- Memory leak
- Startup quá nặng
- UI rendering kém hiệu quả
Nếu không đo được → tối ưu chỉ là đoán.
Sai lầm phổ biến
- Gọi API trên main thread
- Parse JSON nặng trong
ViewModel - Inflate layout phức tạp liên tục
- Xử lý Ads / SDK trong
onCreate
Cách làm đúng (Kotlin)
viewModelScope.launch(Dispatchers.IO) {
val data = repository.loadData()
withContext(Dispatchers.Main) {
_uiState.value = data
}
}
Nguyên tắc
- Main thread = render UI
- Tất cả IO / computation → background
Những thứ làm startup chậm
- Init SDK quá sớm (Ads, Analytics)
- Dùng
ContentProviderkhông cần thiết - Inflate layout phức tạp ngay màn đầu
Chiến lược tối ưu
- Defer initialization
- Lazy load SDK
- Dùng SplashScreen API đúng cách
lifecycleScope.launch {
delay(300)
initAds()
}
👉 User thấy app mở nhanh hơn, dù logic vẫn load sau.
Leak hay gặp
Contextbị giữ trong singleton- Callback không
unregister Fragmentreference trong Adapter
Best practice
- Không giữ Activity
context - Dùng
WeakReferencekhi cần - Clear reference trong
onDestroyView
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
📌 LeakCanary là tool bắt buộc ở production build nội bộ.
Layout (XML)
Vấn đề
- Layout lồng quá sâu
Giải pháp
ConstraintLayout- Flatten hierarchy
DiffUtil+ chuẩnViewHolder
Compose
Vấn đề
- Recomposition quá nhiều
Giải pháp
- State hoisting
rememberSaveable- Tránh tạo object trong Composable
Ads là nguồn gây lag phổ biến
Vấn đề
- Load Ads trên main thread
- Show Ads khi UI chưa ổn định
Best practice Ads
- Preload Ads
- Không init Ads trong
Application.onCreate - Chỉ show Ads khi UI idle
if (ad.isLoaded && lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) {
ad.show(activity)
}
Tool nên dùng
- Android Profiler
- Layout Inspector
- Systrace / Perfetto
- Firebase Performance
📌 Chỉ optimize khi thấy số liệu xấu:
- Main thread không bị block
- Startup < 2 s
- Không memory leak
- UI scroll mượt
- Ads không gây jank
Performance không phải là viết code “thông minh hơn”, mà là đo, phân tích và tối ưu dựa trên dữ liệu thực tế.