Performance Optimization


1. Memory Management

Q: What causes memory leaks in Android?

A memory leak occurs when objects that should be garbage collected are still referenced. Common causes:

Cause Example Fix
Static reference to Context Singleton holding Activity Use Application Context
Non-static inner class Handler, AsyncTask referencing Activity Make static, use WeakReference
Unregistered listeners Broadcast receiver not unregistered Unregister in onStop/onDestroy
Long-lived references ViewModel holding View reference Never store View in ViewModel
Binding not cleared Fragment binding outlives view Null binding in onDestroyView

Q: How do you detect memory leaks?

  • LeakCanary: Automatic detection in debug builds
  • Android Studio Profiler: Memory allocation tracking
  • Heap dump analysis: Find objects that should be GC'd
  • StrictMode: Detect leaked closeable objects

Q: What is the memory hierarchy on Android?

Registers → L1 Cache → L2 Cache → RAM → Disk
(fastest)                              (slowest)

Allocations are cheap, but GC pauses affect UI. Reduce allocations in hot paths (onDraw, adapters).


2. ANR Prevention

Q: What causes ANR (Application Not Responding)?

  • Main thread blocked for >5 seconds for input events
  • BroadcastReceiver not completing within 10 seconds
  • Service not starting within 20 seconds

Q: How do you prevent ANRs?

Don't Do Instead
Database queries on main thread Use Room with coroutines/Flow
Network calls on main thread Use Retrofit suspend functions
Heavy computation on main thread Use withContext(Dispatchers.Default)
Complex View inflation Use ViewStub for lazy inflation
Synchronous file I/O Use withContext(Dispatchers.IO)

Q: How do you debug ANRs?

  1. Check traces.txt in /data/anr/
  2. Look for main thread stack trace
  3. Find blocking operation
  4. Use StrictMode in development to catch early

3. UI Performance

Q: What causes jank (dropped frames)?

Each frame must complete in 16ms for 60fps. Causes of jank:

  • Overdraw (drawing same pixel multiple times)
  • Complex view hierarchies (nested layouts)
  • Heavy onDraw operations
  • Layout thrashing (measure/layout during animation)
  • Main thread blocking

Q: How do you reduce overdraw?

  • Remove unnecessary backgrounds
  • Use clipRect() and quickReject() in custom views
  • Flatten view hierarchy
  • Use tools:showOverdraw to visualize

Q: How do you optimize view hierarchies?

Problem Solution
Nested LinearLayouts Use ConstraintLayout (flat hierarchy)
Views that aren't always shown Use ViewStub for lazy inflation
Complex item layouts Simplify, use merge tag
Frequent layout changes Use TransitionManager for batched changes

Q: RecyclerView optimization?

  • Use DiffUtil for efficient list updates
  • Set setHasFixedSize(true) if size doesn't change
  • Use RecycledViewPool for nested RecyclerViews
  • Avoid inflation in onBindViewHolder
  • Use stable IDs for item animations

4. Rendering Pipeline

Q: Explain Android's rendering pipeline.

  1. Measure: Calculate view sizes
  2. Layout: Position views in hierarchy
  3. Draw: Render to canvas
  4. Sync & Upload: Transfer to GPU
  5. Issue Draw Commands: GPU renders
  6. Swap Buffers: Display on screen

Double buffering ensures smooth display while next frame prepares.

Q: What is hardware acceleration?

GPU handles rendering instead of CPU. Enabled by default. Benefits:

  • Faster for most operations
  • Frees CPU for other work

Some operations aren't hardware-accelerated (complex Path operations). Use software layer for those.


5. Startup Performance

Q: What affects app startup time?

Phase Bottlenecks
Cold start Process creation, class loading, Application init
Warm start Activity creation, but process exists
Hot start Activity resumes, already in memory

Q: How do you optimize cold start?

  • Minimize work in Application.onCreate()
  • Use lazy initialization for non-essential services
  • Defer heavy initialization with App Startup library
  • Use splash screen (Android 12+ SplashScreen API)
  • Reduce class loading (smaller APK, fewer libraries)
  • Enable baseline profiles (ART optimization)

Q: What are Baseline Profiles?

AOT-compiled methods for common user journeys. Reduces JIT compilation on first run. Create using Macrobenchmark, include in release APK.


6. Battery Optimization

Q: What drains battery on Android?

Component Impact
CPU wakeups High—keeping CPU active
Network High—radio power state
GPS Very high—continuous location
Sensors Medium—depends on sensor
Screen Highest—display on

Q: How do you reduce battery usage?

  • Batch network requests (don't wake radio repeatedly)
  • Use WorkManager with constraints (wait for charging)
  • Request coarse location when fine isn't needed
  • Use JobScheduler/WorkManager over AlarmManager
  • Reduce polling; use push notifications
  • Follow Doze and App Standby guidelines

Q: What are Doze and App Standby?

Doze: When device is stationary and screen off, system defers jobs, syncs, alarms. Apps get periodic maintenance windows.

App Standby: Apps not recently used get restricted network and job access.

Handle by using WorkManager with appropriate constraints—system manages execution.


7. Network Optimization

Q: How do you optimize network usage?

Strategy Benefit
Caching Reduce redundant requests
Compression Smaller payloads (gzip)
Pagination Load only needed data
Connection pooling Reuse connections (OkHttp default)
Prefetching Load before needed (WiFi)
Batching Combine multiple requests

Q: How does HTTP caching work?

OkHttp respects Cache-Control headers. Configure cache directory and size. Server controls caching with headers:

  • max-age: Cache duration
  • no-cache: Revalidate each time
  • no-store: Never cache

8. Profiling Tools

Q: What tools are available for performance analysis?

Tool Purpose
Android Studio Profiler CPU, memory, network, energy
Systrace / Perfetto System-wide tracing
Layout Inspector View hierarchy, Compose recomposition
GPU Profiler Rendering performance
Macrobenchmark Startup and runtime benchmarks
StrictMode Detect I/O on main thread

Q: How do you use StrictMode effectively?

Enable in debug builds only:

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

Catches disk/network access on main thread early in development.


Quick Reference

Area Key Points
Memory Leaks No static Context; null bindings; unregister listeners; use LeakCanary
ANR No I/O on main thread; use coroutines; check traces.txt for debugging
UI Performance Flatten hierarchies; reduce overdraw; use DiffUtil; profile with Systrace
Startup Lazy init; defer work; baseline profiles; minimize Application.onCreate()
Battery Batch requests; use WorkManager; respect Doze; prefer push over polling
Network Cache responses; compress payloads; paginate; batch requests

results matching ""

    No results matching ""