Performance optimization is a core skill in Android development, involving multiple dimensions including memory, UI, network, and battery.
1. Memory Optimization
Memory Leak Detection
- LeakCanary: Automatic memory leak detection
- Android Profiler: Real-time memory allocation monitoring
- MAT: Analyze hprof files, find dominator tree
Memory Optimization Strategies
kotlin// 1. Use SparseArray instead of HashMap<Integer, Object> val sparseArray = SparseArray<String>() // 2. Image memory optimization val options = BitmapFactory.Options().apply { inSampleSize = 2 // Scale sampling inBitmap = reusableBitmap // Bitmap reuse } // 3. Use LRU cache val cache = LruCache<String, Bitmap>(maxMemory / 8)
Large Image Optimization
- Use inSampleSize compression
- Use WebP format
- Use image loading libraries (Glide, Picasso, Coil)
2. UI Rendering Optimization
Layout Optimization
xml<!-- 1. Reduce layout hierarchy --> <merge> <!-- Reduce one ViewGroup layer --> <include> <!-- Reuse layout --> <ViewStub> <!-- Lazy loading -->
Avoid Overdraw
kotlin// 1. Remove unnecessary backgrounds window.setBackgroundDrawable(null) // 2. Use clipRect to reduce drawing area canvas.clipRect(left, top, right, bottom)
List Optimization
kotlin// RecyclerView optimization recyclerView.setHasFixedSize(true) recyclerView.setItemViewCacheSize(20) recyclerView.setRecycledViewPool(pool)
3. Network Optimization
Request Optimization
kotlin// 1. Use connection pool okHttpClient.connectionPool(ConnectionPool(5, 5, TimeUnit.MINUTES)) // 2. Enable Gzip compression okHttpClient.addInterceptor(GzipInterceptor()) // 3. Set reasonable timeouts okHttpClient.connectTimeout(10, TimeUnit.SECONDS)
Data Caching
kotlin// 1. Use Cache-Control @Headers("Cache-Control: max-age=3600") // 2. Local cache strategy val cache = Cache(cacheDir, 10 * 1024 * 1024) // 10MB
4. Battery Optimization
Doze Mode and App Standby
- Understand system power saving mechanisms
- Use high-priority FCM messages
- Batch background tasks
Background Task Optimization
kotlin// Use WorkManager instead of background Service val constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .setRequiresBatteryNotLow(true) .build() val workRequest = PeriodicWorkRequestBuilder<SyncWorker>(1, TimeUnit.HOURS) .setConstraints(constraints) .build()
Location Optimization
kotlin// Use balanced accuracy mode locationRequest.priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY // Remove location updates promptly fusedLocationClient.removeLocationUpdates(callback)
5. Package Size Optimization
Resource Optimization
groovyandroid { // 1. Remove unused resources lintOptions { checkReleaseBuilds false } // 2. Resource compression shrinkResources true minifyEnabled true // 3. Keep only specific languages resConfigs "zh", "en" }
Code Optimization
groovy// 1. Use ProGuard/R8 obfuscation proguardFiles getDefaultProguardFile('proguard-android-optimize.txt') // 2. Dynamic feature modules android { dynamicFeatures = [':feature1', ':feature2'] }
6. Startup Optimization
- Async initialization
- Lazy loading non-essential components
- Use SplashScreen API
7. Common Performance Analysis Tools
| Tool | Purpose | Usage Scenario |
|---|---|---|
| Android Profiler | CPU/Memory/Network monitoring | Real-time app performance monitoring |
| Systrace | System-level performance analysis | Analyze frame rate, startup time |
| Layout Inspector | Layout hierarchy analysis | Optimize layout nesting |
| GPU Overdraw | Overdraw detection | Optimize drawing performance |
| LeakCanary | Memory leak detection | Detect leaks during development |
| StrictMode | Violation detection | Detect main thread IO, etc. |
| Battery Historian | Battery analysis | Analyze power consumption |
8. Systrace Usage Example
bash# Capture trace python systrace.py -a com.example -o trace.html sched gfx view # Analysis focus # 1. Check frame rate (Frame) for dropped frames # 2. Check if UI thread is blocked # 3. Check GC frequency
9. Performance Optimization Checklist
- Test performance in Release mode
- Verify on low-end devices
- Monitor online performance data
- Regular performance regression testing
- Establish performance baseline metrics
Key Points
- Master common memory optimization methods
- Understand UI rendering principles and optimization methods
- Familiar with usage of various performance analysis tools
- Understand best practices for battery optimization
- Master APK slimming technical solutions