Performance optimization and profiling

Alex Chen Jan 2026
2 tabs
package com.example.myapp.utils

import android.os.Build
import android.os.StrictMode
import android.os.Trace
import timber.log.Timber

object PerformanceUtils {

    fun enableStrictMode() {
        if (BuildConfig.DEBUG) {
            StrictMode.setThreadPolicy(
                StrictMode.ThreadPolicy.Builder()
                    .detectAll()
                    .penaltyLog()
                    .build()
            )

            StrictMode.setVmPolicy(
                StrictMode.VmPolicy.Builder()
                    .detectAll()
                    .penaltyLog()
                    .build()
            )
        }
    }

    inline fun <T> trace(sectionName: String, block: () -> T): T {
        Trace.beginSection(sectionName)
        return try {
            block()
        } finally {
            Trace.endSection()
        }
    }

    inline fun <T> measureTime(tag: String, block: () -> T): T {
        val start = System.currentTimeMillis()
        return try {
            block()
        } finally {
            val duration = System.currentTimeMillis() - start
            Timber.d("$tag took ${duration}ms")
        }
    }

    fun logMemoryUsage() {
        val runtime = Runtime.getRuntime()
        val usedMemory = (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024
        val maxMemory = runtime.maxMemory() / 1024 / 1024
        val availableMemory = maxMemory - usedMemory

        Timber.d("Memory: Used=${usedMemory}MB, Max=${maxMemory}MB, Available=${availableMemory}MB")
    }
}

// Usage in Application class:
class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()

        if (BuildConfig.DEBUG) {
            PerformanceUtils.enableStrictMode()

            // Setup LeakCanary (automatically enabled in debug)
        }
    }
}

// Usage in code:
// PerformanceUtils.trace("LoadPosts") {
//     repository.loadPosts()
// }
//
// PerformanceUtils.measureTime("Database Query") {
//     database.postDao().getAllPosts()
// }
2 files · kotlin Explain with highlit

Android performance optimization ensures smooth 60fps UI and efficient resource usage. I use Android Profiler to monitor CPU, memory, network, and energy. Layout Inspector identifies overdraw and deep view hierarchies. Systrace captures system-level traces. LeakCanary detects memory leaks. Optimize layouts—use ConstraintLayout, avoid nested weights, flatten hierarchies. RecyclerView with DiffUtil minimizes list updates. Image loading uses appropriate sizes and caching. Background work uses WorkManager instead of constant services. Database queries use indices and batch operations. Avoid work on main thread—use coroutines for async operations. Strict mode catches common mistakes. APK Analyzer shows size breakdown. Benchmarking libraries measure performance regressions. Profile regularly to maintain responsive apps.