preface

One of the new features that came with the recent 3.3 Update to the Android Studio Stable is a new generation of code compression tools called R8, which we’ll cover in detail in this article. Before you read this article:

  • Android uses Proguard to reduce code

About the R8

As Android developers, we all know that reducing the size of APK is an important part of every project, and code reduction helps reduce the size of APK by removing unused code and resources, and makes the actual code take up less space (also known as obfuscation). So R8 is a tool designed to make the code reduction process faster and more efficient. R8 is now open source:

  • View R8 source code

The background and history of the R8 tool

We developers use Java or Kotlin to write program code, and then convert it to Dalvik bytecode (.dex) required by Android devices. The whole process can be simply shown in the following figure:

Java bytecode (.class)
ProGuard
Dx compiler
Dalvik bytecode (.dex)
20-50%
20%

The performance of the build process is so important to developers that in 2015, the Google Android team introduced the compiler Jack and Jill. They integrate the functionality of the Java compiler, ProGuard, and Dalvik compiler in a single step:

The D8 compiler

This still leaves room for optimizing the build process, and R8 is a derivative of D8, designed to integrate the functionality of ProGuard and D8:

The R8 and Proguard

The R8 performs all the shrinking, desugaring, and switching to Dalvik bytecode (dexing) in one fell swoop.

The shrinking process provides three important functions:

  • Compression: Remove useless classes, sections, methods, etc from code.
  • Optimization: Makes code smaller and more efficient at the instruction level.
  • Obfuscation: Rename the rest of the classes, fields, and methods in the code with short, meaningless names.

Compared to the current code reduction solution Proguard, R8 reduces code faster while improving output size. Here’s a comparison using some data from Benchmark:

  • See Github for more data details

How to use R8

R8 is very simple. After Android Studio is upgraded to version 3.3 or above, simply add the following command to your project gradle.properties:

android.enableR8=true
Copy the code

R8 normal mode is compatible with Proguard. If Proguard has been used in the original project, directly enable R8. R8 also has full mode and is not directly compatible with Proguard. You can also set the following in the gradle.properties file:

android.enableR8.fullMode=true
Copy the code

This article is personally original, please indicate the source of reprint.