R8

Also known as: R8 compiler

On this page 7

R8 is the Android code shrinker and optimizing compiler that turns Java and Kotlin bytecode into compact DEX files while removing unused code, rewriting the remaining code for speed and renaming symbols to short identifiers. In mobile performance work, the R8 compiler is the main build-time lever for smaller APK and AAB downloads, faster class loading and leaner runtime behavior on Android devices.

R8 became the default shrinker in Android Gradle Plugin 3.4 and replaced the older two-step pipeline of ProGuard plus the D8 dexer. It reads the same ProGuard keep rules, so most projects migrated without rewriting configuration, yet R8 applies more aggressive whole-program optimizations than ProGuard ever did for Android targets.

How the R8 compiler processes an Android app

R8 works as a whole-program compiler: it sees the app code and all library dependencies at once, which lets it prove that a class, method or field is never reachable and then delete it. The process starts from entry points, such as activities declared in the manifest and classes named in keep rules, and traces every reference from there.

Everything the tracer cannot reach is discarded, a step usually called tree shaking. The surviving code is then optimized, obfuscated and emitted as DEX bytecode in a single pass, which is faster than the historical sequence of separate tools. The following table summarizes the stages that run inside one R8 invocation.

StageWhat happensMain effect
ShrinkingUnreachable classes, methods and fields are removedSmaller DEX files
OptimizationInlining, class merging, constant propagationLess code, fewer calls
ObfuscationNames are replaced with short identifiersSmaller string pool, harder reverse engineering
DesugaringNewer Java language features are rewritten for older Android versionsWider API level support
DexingOptimized bytecode is converted to DEX formatOutput ready for ART
Stages inside a single R8 build step

Resource shrinking is a related but separate feature. When shrinkResources is enabled, the build removes unreferenced drawables, layouts and strings after R8 has shown which code, and therefore which resource IDs, is still in use.

Optimizations that affect runtime performance

The size savings of R8 are well known, but its runtime optimizations matter just as much for mobile performance. Fewer classes mean less work for the Android Runtime (ART) during class loading and verification, which shortens app startup time, and inlined code avoids call overhead on hot paths.

OptimizationMechanismPerformance benefit
Method inliningSmall or single-caller methods are copied into callersFewer invocations on hot paths
Class mergingClasses with one subclass or implementation are combinedFewer classes to load and verify
DevirtualizationInterface calls with one target become direct callsCheaper dispatch
Enum unboxingSimple enums are replaced with integer constantsFewer allocations
Constant propagationKnown values replace field reads and branchesDead branches removed
Startup layoutClasses from a startup profile are placed in the primary DEXFewer page faults at launch
Typical R8 optimizations and their runtime impact

Recent Android Gradle Plugin versions can feed a startup profile to R8 so that classes needed during launch are grouped together. This complements Baseline Profiles, which tell ART which methods to compile ahead of time; R8 improves the DEX layout, while Baseline Profiles improve compilation coverage.

R8 compared with ProGuard and D8

R8 is often confused with ProGuard because both accept the same rule syntax, but they are different tools. ProGuard is an independent Java bytecode optimizer that produces Java class files, whereas R8 is built by the Android toolchain team and emits DEX directly. D8 is the plain dexer that R8 extends.

ToolOutputShrinks codeTypical role today
R8DEX bytecodeYes, plus optimizationDefault for release builds
ProGuardJava class filesYesLegacy Android setups, non-Android Java
D8DEX bytecodeNoDebug builds without minification
How R8 differs from neighboring build tools

Since Android Gradle Plugin 8.0, R8 runs in full mode by default. Full mode makes fewer assumptions to stay compatible with ProGuard behavior, so it removes more code but also requires more precise keep rules for code accessed through reflection.

Configuring R8 in a release build

R8 is activated by setting isMinifyEnabled = true in the release build type, usually together with isShrinkResources = true and the default file proguard-android-optimize.txt. Project-specific rules go into a file such as proguard-rules.pro, and library modules ship consumer rules that are merged automatically into the app configuration.

  • -keep preserves a class and its members from removal and renaming.
  • -keepclassmembers preserves only members, for example fields used by a JSON serializer.
  • -keepattributes retains metadata such as annotations and generic signatures.
  • -dontobfuscate disables renaming, which is useful while diagnosing a problem but costs size.

Every release build produces a mapping file that links obfuscated names back to the original ones. This file must be archived for each released version and uploaded to the crash analytics service or the Google Play Console, otherwise stack traces from production devices are unreadable. The retrace tool uses the same file to decode traces locally.

SituationRecommended approachReason
New appEnable R8 full mode from the first releaseRules grow with the code
Heavy reflectionAdd narrow keep rules per classBroad rules waste the savings
Library authorPublish consumer keep rulesApps stay correct without guessing
Startup-critical appCombine R8 with startup and Baseline ProfilesLayout and compilation both improve
Choosing an R8 configuration strategy

Limitations and common R8 mistakes

The most frequent failure is a runtime crash caused by missing keep rules. R8 cannot see code reached through reflection, string-based class lookups, JNI or some serialization libraries, so it may delete or rename classes that are needed at runtime. These errors appear only in release builds, which is why release variants must be tested before shipping.

SymptomLikely causeFix
ClassNotFoundExceptionClass used only through reflection was removedAdd a targeted keep rule
Empty JSON fieldsModel fields were renamedKeep members or use annotations
Unreadable stack tracesMapping file not uploadedStore and upload mapping per release
Little size reductionOverly broad keep rulesNarrow the rules and audit libraries
Symptoms, causes and fixes

Size reductions vary widely. Apps with large dependency trees often see the DEX size shrink by a substantial fraction, while small apps with few libraries gain less. Build time also increases, because whole-program analysis is more expensive than plain dexing, so many teams run R8 only for release and benchmark variants.

The simple explanation

Imagine packing for a trip with a large toolbox. R8 looks at every tool, checks which ones the trip actually needs and leaves the rest at home. It then labels the remaining tools with short tags instead of long names so the box is lighter still.

For an Android app, this means a smaller download and a faster start. The only catch is that R8 can remove something that the app uses in a hidden way, so developers add notes that say keep this, it is needed.

How it is used in practice

A team maintaining a shopping app for Android notices that its release AAB has grown past 40 MB and that cold starts on low-end phones take more than two seconds. The app uses a networking library, a JSON parser, an image loader and several analytics SDKs, but release builds had never enabled minification.

The team turns on R8 full mode with resource shrinking, adds keep rules for the data models parsed by reflection and adds a startup profile generated with Macrobenchmark. Release testing reveals one crash in a payment screen, fixed with a single -keepclassmembers rule. After the change, the download size drops noticeably and the cold start on the slowest test device improves by a few hundred milliseconds. The mapping file is now uploaded automatically with each release, so crash reports remain readable.