Mobile EngineeringVol. 22 · Mobile
0 / 0

Shelves / Mobile Engineering

MB·06

Performance and Memory

Making apps fast and frugal on real devices: cold, warm and hot startup and how to shorten them, app size and why it affects installs, memory limits, leaks and low-memory kills, image memory and decoding at the right size, smooth lists and rendering, and measuring it all in the lab and in the field (Macrobenchmark, Baseline Profiles, Perfetto, Instruments, Android vitals, MetricKit); with a lab that decodes a 12-megapixel photo into 48 MB of memory, then decodes it at a quarter of the size in a third of the time.

14 topics · ~7 min read · 16-question quiz
Updated Suggest a correction

Start here: phones are not small laptops

A mid-range phone has a fraction of a laptop's CPU, memory bandwidth and thermal headroom, shares its memory with every other app, and throttles when warm. Users notice three things first:

What users notice Measure Typical target
how long the app takes to open cold start time to first useful frame under ~1–2 s on a mid-range device
whether scrolling and animations are smooth dropped frames, slow frames almost none (chapter 01)
whether it crashes or freezes crash and ANR rates Google Play flags apps above ~1.09% user-perceived crash rate or ~0.47% ANR rate

And one thing they don't see until it hurts: memory. Apps that use too much are killed in the background (losing state) or crash with out-of-memory errors. The most common culprit is images.

One photo, measured

Handling a 12-megapixel (4000 × 3000) photo Memory Time (lab CPU)
the JPEG file 3 MB on disk —
decoded at full size 48 MB (4 bytes per pixel) 104 ms
decoded at ¼ scale during decoding 3 MB 36 ms
full decode, then resized to a 360 × 270 card 0.39 MB card, after 48 MB peak +157 ms
a list of 50 cards from full-size bitmaps 2.4 GB —
the same list at card size 19 MB —

The file size says nothing about memory: a decoded image costs width × height × 4 bytes. Decoding straight to the size you'll display is faster and uses a fraction of the memory.

How deep to go

Volume 17 defines six mastery levels. For mobile performance:

Level What you can do
L1 Name startup types, jank, leaks and size as performance concerns
L2 Use image libraries, lazy initialisation and release builds correctly
L3 Explain startup phases, bitmap memory, GC/ARC and rendering pipelines
L4 Find the cause of slow starts, leaks and jank from traces and heap dumps
L5 Set performance budgets and design an app to meet them on target devices
L6 Keep them met release after release with field monitoring and regression tests

Startup

What happens on a cold start, and what you control:

Phase Android iOS Your levers
process creation, code loading zygote fork, DEX/ART code dyld loads binaries and frameworks fewer, smaller dependencies; fewer dynamic frameworks
app initialisation Application.onCreate, content providers, DI graph main, App init, static initialisers lazy init; App Startup library; defer analytics, SDKs, remote config fetches
first screen activity creation, first composition and layout first scene and view show cached data immediately; avoid network on the critical path
  • Baseline Profiles (Android) ship a list of hot methods so they're compiled ahead of time at install, commonly improving startup and scrolling noticeably; generate them with Macrobenchmark.
  • Measure: adb shell am start -W and Macrobenchmark (StartupTimingMetric) on Android; Instruments' App Launch template and MetricKit launch metrics on iOS; field startup percentiles from vitals.
  • Set a budget ("cold start p90 < 1.5 s on our reference mid-range device") and test it in CI.

App size

  • Android: App Bundles (Play delivers only the code and resources a device needs), R8 shrinking and optimisation, resource shrinking, vector drawables and WebP, dynamic feature modules for rarely used features.
  • iOS: app thinning, asset catalogs, removing unused architectures and assets, on-demand resources.
  • Audit dependencies: one convenience SDK can add megabytes and startup time. Track size per release.

Memory

  • Each app has a heap limit (Android largeHeap is not a fix) and competes with others; backgrounded apps are killed first when memory is low.
  • Images (the lab): decode at the displayed size (inSampleSize / ImageDecoder target size on Android; ImageIO thumbnail APIs on iOS), use image libraries (Coil, Glide, Kingfisher, SDWebImage) that size, cache and reuse bitmaps, and prefer hardware bitmaps where available.
  • Caches: bounded LRU caches sized as a fraction of available memory; respond to memory warnings (onTrimMemory, didReceiveMemoryWarning) by trimming.
  • Leaks: LeakCanary in debug builds on Android; Instruments' Leaks and the Memory Graph debugger on iOS; review closures capturing self ([weak self]) and long-lived listeners.

Rendering and lists

  • Lazy lists (LazyColumn, SwiftUI List/LazyVStack) create rows only for what's visible; give them stable keys (chapter 02) and cheap rows.
  • Avoid deep, nested layouts and overdraw (drawing the same pixel many times); flatten where possible.
  • Keep animations on properties the system can animate cheaply (transforms, opacity).
  • Profile with the Compose layout inspector and Perfetto, or Instruments' Animation Hitches.

Measuring in the field

Platform Field data
Android Android vitals in Play Console (crash and ANR rates, startup, slow and frozen frames, excessive wake-ups, by device and version); Firebase Performance or your own telemetry
iOS Xcode Organizer metrics; MetricKit payloads (launch time, hangs, memory, disk writes, energy) delivered daily to the app

Watch distributions by device class and app version: regressions show up first on low-end devices, and a new release's metrics tell you whether to continue its rollout (chapter 09).

Common traps

  • Full-size bitmaps in lists and thumbnails.
  • Heavy work in Application.onCreate or static initialisers.
  • Unbounded caches.
  • Measuring debug builds (much slower, and different) or only flagships.
  • SDK sprawl inflating size and startup.

Lab: what an image costs in memory

Setup. Python with Pillow and NumPy on the lab machine. A synthetic 12-megapixel photo (4000 × 3000, smooth gradients plus noise so it compresses like a real photo) saved as a quality-85 JPEG. Decoding into RGBA (4 bytes per pixel, as phones typically store bitmaps), median of three runs. Pillow's JPEG draft mode decodes at a reduced scale (1/2, 1/4, 1/8) during decoding using the JPEG format's DCT scaling, the same idea as Android's inSampleSize and iOS's ImageIO thumbnail decoding.

Results

Operation Pixels Memory Time
JPEG on disk — 3.0 MB —
full decode 4000 × 3000 48 MB 104 ms
decode at ¼ scale 1000 × 750 3.0 MB 36 ms
full decode, then high-quality resize to a 360 × 270 card 360 × 270 0.39 MB (after a 48 MB peak) +157 ms for the resize
50 cards backed by full-size bitmaps — 2.4 GB —
50 cards at card size — 19 MB —

What it shows

  • Memory is pixels × 4, not file size. A 3 MB file became 48 MB in memory; fifty of them would exceed any phone's per-app limit many times over.
  • Decoding small is cheaper in every way: 16× less memory and ~3× faster than a full decode, and without the 48 MB peak that can trigger an out-of-memory crash on its own.
  • Decode-then-resize is the worst path: it pays the full decode, the peak memory and an expensive resample.
  • On phones, the CPU is slower but hardware JPEG decoders and image libraries help; the memory arithmetic is identical. Better still, have the server or CDN send an image already sized for the slot (chapter 04), so the phone never downloads 3 MB for a 360-pixel card.

Try it yourself

  1. Decode at ½ and ⅛ scale and plot memory and time.
  2. Save the photo as WebP and AVIF at similar visual quality and compare file sizes and decode times.
  3. In an Android app, load the same photo into a list with Coil and without (plain BitmapFactory.decodeFile), and compare the memory profiler's graph.
  4. On iOS, compare UIImage(contentsOfFile:) with CGImageSourceCreateThumbnailAtIndex at 360 px.

Revision sheet: performance and memory

Key ideas

  • Users notice startup, smoothness and crashes; memory problems show as background kills and OOM crashes.
  • Startup: process and code loading, app initialisation, first screen; lazy init, Baseline Profiles, cached first screens; budgets in CI.
  • Size: App Bundles, R8, resource shrinking, thinning; audit SDKs.
  • Memory: bitmaps are pixels × 4; decode at display size; bounded caches; respond to memory warnings; find leaks with LeakCanary and Instruments.
  • Lazy lists with keys; flat layouts; cheap animations.
  • Field metrics (Android vitals, MetricKit) by device class and version.

Numbers to remember

  • Lab: 12 MP photo → 48 MB decoded; ¼-scale decode 3 MB in 36 ms vs 104 ms; 50 full-size cards 2.4 GB.
  • Play bad-behaviour thresholds ≈ 1.09% user-perceived crash rate, 0.47% ANR rate (at the time of writing).

Glossary

  • Cold / warm / hot start: from no process / recreated UI / resumed UI.
  • Baseline Profile: a list of hot code compiled at install time.
  • inSampleSize / thumbnail decoding: decoding images at reduced resolution.
  • Retain cycle: mutual strong references preventing deallocation (ARC).
  • MetricKit: Apple's on-device performance and diagnostics reports.