1️⃣ 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.
2️⃣ Main Thread – nguyên nhân số 1 gây lag & ANR
❌ 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
3️⃣ Startup Time – lý do user thoát app sớm
❌ Những thứ làm startup chậm
- Init SDK quá sớm (Ads, Analytics)
- Dùng ContentProvider khô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.
4️⃣ Memory Leak – app chạy lâu là sập
❌ Leak hay gặp
- Context bị giữ trong singleton
- Callback không unregister
- Fragment reference trong Adapter
✅ Best practice
- Không giữ Activity context
- Dùng WeakReference khi 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ộ.
5️⃣ UI Performance: XML vs Compose
XML
❌ Layout lồng quá sâu
❌ RecyclerView không dùng DiffUtil
✅ Giải pháp:
- ConstraintLayout
- Flatten hierarchy
- DiffUtil + ViewHolder chuẩn Compose
❌ Recomposition quá nhiều
❌ State đặt sai chỗ
✅ Giải pháp:
- State hoisting
- rememberSaveable
- Tránh tạo object trong Composable
6️⃣ Ads & Performance – phần nhiều dev bỏ qua
Ads là nguồn gây lag rất phổ biến, nhất là:
- 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)
}
7️⃣ Đo lường – không đo thì đừng tối ưu
Tool nên dùng
- Android Profiler
- Layout Inspector
- Systrace / Perfetto
- Firebase Performance
📌 Chỉ optimize khi thấy số liệu xấu
8️⃣ Checklist nhanh (dùng cho team)
- Main thread không bị block
- Startup < 2s
- Không memory leak
- UI scroll mượt
- Ads không gây jank
9️⃣ Kết luận
Performance không phải là viết code “thông minh hơn”,
mà là viết code có ý thức về runtime.
This article is inspired by various Android performance discussions and my own production experience.
Top comments (0)