--- title: "Android App Startup Surgery: Baseline Profiles, Dex Layout, and the Retention Metric Nobody Talks About" published: true description: "Master Android startup optimization with Macrobenchmark, Baseline Profiles, and dex layout strategies. Cold start under 500ms and warm start under 300ms aren't arbitrary — they're tied directly to Day-1 retention." tags: [kotlin, android, mobile, performance] canonical_url: https://mvpfactory.co/blog/android-startup-surgery-baseline-profiles-dex-layout --- ## What we're building toward By the end of this workshop you will have a fully instrumented startup pipeline: Macrobenchmark capturing real metrics in CI, a Baseline Profile bundled into your release APK, and a clear understanding of why dex layout matters even after you've done everything else right. We'll also cover the three start types and the budget thresholds that actually correlate with Day-1 user retention. ## Prerequisites - Android Studio Hedgehog or later - A physical device or managed emulator (Macrobenchmark does not run meaningfully on emulators) - `minifyEnabled = true` on your release build variant - `androidx.benchmark:benchmark-macrobenchmark` added to your benchmark module --- ## Step 1: Instrument before you touch anything Most teams optimize blind — they add `StrictMode`, eyeball Logcat, and call it done. That is guesswork. The right tool is `MacrobenchmarkRule`. It runs in a real process, isolated from your test APK, against a release build. Here is the minimal setup to get this working:
kotlin
@RunWith(AndroidJUnit4::class)
class StartupBenchmark {
@get:Rule
val benchmarkRule = MacrobenchmarkRule()
@Test fun coldStartup() = benchmarkRule.measureRepeated( packageName = "com.example.myapp", metrics = listOf(StartupTimingMetric()), iterations = 10, startupMode = StartupMode.COLD ) { pressHome() startActivityAndWait() } }
Run this against your **release** build — not debug. JIT behavior differs dramatically between the two, and you are measuring the wrong thing if you benchmark debug. The output gives you `timeToInitialDisplayMs` and `timeToFullDisplayMs` as percentile distributions. P50 matters. P95 is what your worst users actually experience. Add this benchmark to your CI pipeline and track it across releases. You cannot improve what you do not measure. --- ## Step 2: Baseline Profiles — AOT for your critical path Here is the gotcha that will save you hours: Baseline Profiles are not a magic switch. They are a compilation hint file that tells the ART runtime which classes and methods to compile ahead-of-time on first install or update. Without a Baseline Profile, the class loader verifies and JIT-compiles your startup path on every cold launch until the device runs its background dexopt job — typically overnight, idle, on charge. That means your Day-1 users are running interpreted bytecode. If your app is something like [HealthyDesk](https://play.google.com/store/apps/details?id=com.healthydesk) — surfacing break reminders and desk exercises where every launch competes with a developer's attention — a sluggish cold start defeats the value proposition before the first screen renders. Generate a profile from a real user journey:
kotlin
@RunWith(AndroidJUnit4::class)
class BaselineProfileGenerator {
@get:Rule
val rule = BaselineProfileRule()
@Test fun generate() = rule.collect( packageName = "com.example.myapp" ) { pressHome() startActivityAndWait() // Drive your critical user journey here } }
The output is a `baseline-prof.txt` placed in `src/main/`. The Android Gradle Plugin bundles it into the APK. Play Store triggers compilation on install via `speed-profile` mode. Verify it worked post-install with:
bash
adb shell dumpsys package com.example.myapp | grep compilationFilter
You want to see `speed-profile`. Anything else means the profile was not picked up. --- ## Step 3: Dex layout and the class loader tax Even with a Baseline Profile in place, class loading order matters. The dex file format stores classes linearly. If your startup path loads `MainActivity` but `MainActivity` sits at offset 8,000 in the dex, the class loader pays a seek cost on every cold start. The `dexlayout` tool reorders classes based on the profile, minimizing disk reads. The Gradle plugin handles this automatically when you provide a Baseline Profile — but only for release builds with `minifyEnabled = true`. The docs do not make this dependency obvious. Here is what the combined optimization layers actually deliver: | Optimization layer | Cold start reduction | Complexity | |---|---|---| | No optimization (baseline) | 0% | — | | Baseline Profile only | 10–30% | Low | | Dex layout reordering | 5–15% additional | Low (automatic) | | App Startup library (lazy init) | 5–20% | Medium | | Combined approach | 25–50% | Medium | The combined approach routinely moves apps from 800ms cold starts down into the 400–450ms range in production. --- ## The three start types and your budget Let me show you a pattern I use in every project — a reference table I keep open during performance reviews: | Start type | Definition | Target budget | |---|---|---| | Cold | App process not in memory | < 500ms | | Warm | Activity recreated, process alive | < 300ms | | Hot | Activity brought to foreground | < 100ms | Warm starts are where most teams leave performance on the table. If your `Activity.onCreate()` is re-running expensive initialization that should live in `Application` — or worse, hitting the network — your warm start collapses toward cold start territory. The 300ms budget is tight, and it is the one most commonly blown by misplaced init logic. --- ## Gotchas **Benchmarking debug builds.** JIT is not representative of production ART behavior. Always benchmark release. **Generating profiles from shallow journeys.** A profile that only captures `startActivityAndWait()` without driving real navigation will miss methods loaded during your first user interaction. Drive a realistic critical path in your generator test. **Assuming Play Store always compiles.** On older devices or low-storage conditions, Play may skip profile-guided compilation. Verify on real hardware, not just emulators. **Warm start neglect.** Google's data shows startup latency above 500ms measurably increases Day-1 abandonment on cold launches. But teams fix cold start, ship, and ignore warm start entirely. Audit `Activity.onCreate()` before closing the ticket. --- ## Three takeaways 1. **Instrument before you optimize.** Add Macrobenchmark to CI and track P50 and P95 startup times across every release. 2. **Ship a Baseline Profile with every release.** Generate it from real user journeys, commit it to source, and verify via `dumpsys` that `speed-profile` appears post-install. 3. **Treat warm start as a first-class metric.** The 300ms budget is tight. Audit `Activity.onCreate()` for work that should be deferred or moved upstream. **Further reading:** [Android Baseline Profiles documentation](https://developer.android.com/topic/performance/baselineprofiles/overview) · [Macrobenchmark guide](https://developer.android.com/topic/performance/benchmarking/macrobenchmark-overview) 



