Steps to Speed Up/Optimize Android Studio Gradle Build Process.

By | October 1, 2017

Even with good hardware configuration for the system, we often end up with slow gradle build process in Android Studio.

So here I will discuss some steps to Speed up Android Gradle build.

1. Stay Up to Date

Make sure you have the latest Android Studio and have the latest build tools updated.

2. Create a build variant for Development

You can simply create a flavour for Development. just like this

 android {
  ...
  defaultConfig {...}
  
  buildTypes {...}
  
  productFlavors {
  
    // When building a variant that uses this flavor, the following configurations
    // override those in the defaultConfig block.
    dev {
      // To avoid using legacy multidex when building from the command line,
      // set minSdkVersion to 21 or higher. When using Android Studio 2.3 or higher,
      // the build automatically avoids legacy multidex when deploying to a device running
      // API level 21 or higher—regardless of what you set as your minSdkVersion.
      minSdkVersion 21
      versionNameSuffix "-dev"
      applicationIdSuffix '.dev'
    }

    prod 
    {
      // If you've configured the defaultConfig block for the release version of
      // your app, you can leave this block empty and Gradle uses configurations in
      // the defaultConfig block instead. You still need to create this flavor.
      // Otherwise, all variants use the "dev" flavor configurations.
    }
    
  }
}

If your build configuration already uses product flavors to create different versions of your app, you can combine the “dev” and “prod” configurations with those flavors by using flavor dimensions. For example, if you already configure a “demo” and “full” flavor, you can use the following sample configuration to create combined flavors, such as “devDemo” and “prodFull”:

android {
  ...
  defaultConfig {...}
  buildTypes {...}// Specifies the flavor dimensions you want to use. The order in which you
  // list each dimension determines its priority, from highest to lowest,
  // when Gradle merges variant sources and configurations. You must assign
  // each product flavor you configure to one of the flavor dimensions.

  flavorDimensions 
"stage", "mode"

  productFlavors 
{
    dev {
      dimension "stage"
      minSdkVersion 21
      versionNameSuffix "-dev"
      applicationIdSuffix '.dev'
      ...
    }

    prod 
{
      dimension "stage"
      ...
    }

    demo 
{
      dimension "mode"
      ...
    }

    full 
{
      dimension "mode"
      ...
    }
  }
}

3. Avoid compiling unnecessary resources

If you are not testing for big screens, you can just avoid those resources.

android {
  ...
  productFlavors {
    dev {
      ...
      // The following configuration limits the "dev" flavor to using
      // English stringresources and xxhdpi screen-density resources.
      resConfigs "en", "xxhdpi"
    }
    ...
  }
}

4. Use Static Dependency Versions

Avoid using these kind of dependencies

      'com.android.tools.build:gradle:2.+'

It makes android search for newer versions every 24 hours and you may be using different versions of the same library everyday.

5. Enable Offline Gradle Build

If you are on a slow network connection, you can enable offline build in Gradle Settings.

To enable offline build, you can follow these steps.

To use Gradle offline when building with Android Studio, proceed as follows:

  1. Open the Preferences window by clicking File > Settings (on Mac, Android Studio > Preferences).
  2. In the left pane, click Build, Execution, Deployment > Gradle.
  3. Check the Offline work checkbox.
  4. Click Apply or OK.

6. Enable configuration on demand

For Gradle to know exactly how to build your app, the build system configures all modules in your project, and their dependencies, before every build (even if you are building and testing only a single module). This slows down the build process for large multi-module projects. To tell Gradle to configure only the modules that you want to build, enable configuration on demand by following these steps:

Open the Preferences window by clicking File > Settings (on Mac, Android Studio > Preferences).
In the left pane, click Build, Execution, Deployment > Compiler.
Check the Configure on demand checkbox.
Click Apply or OK.

7. Configure dexOptions and enable library pre-dexing

The Android plugin provides the dexOptions block so you can configure the following DEX build properties, which may improve build speeds:

preDexLibraries: Declares whether to pre-dex library dependencies so that your incremental builds are faster. Because this feature may slow down your clean builds, you may want to disable this feature for your continuous integration server.
maxProcessCount: Sets the maximum number of threads to use while running dex-in-process. The default is 4.
javaMaxHeapSize: Sets the maximum heap size for the DEX compiler. Instead of setting this property, however, you should increase Gradle’s heap size (which is shared with the DEX compiler when dex-in-process is enabled).
For example:

android {
  ...
  dexOptions {
    preDexLibraries true
    maxProcessCount 8
    // Instead of setting the heap size for the DEX process, increase Gradle's
    // heap size to enable dex-in-process. To learm more, read the next section.
    // javaMaxHeapSize "2048m"
  }
}

Increase Gradle’s heap size and enable dex-in-process

The following sample sets the Gradle’s heap size to 2048 MB in your project’s gradle.properties file:

org.gradle.jvmargs = -Xmx2048m

More in gradle properties

// Enable Gradle Daemon
org.gradle.daemon=true
// Enable Configure on demand
org.gradle.configureondemand=true
//Enable parallel builds
org.gradle.parallel=true
// Enable Build Cache
android.enableBuildCache=true
//Enable simple gradle caching
org.gradle.caching=true
// Increase memory allotted to JVM
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

Convert images to WebP

You can use Android Studio to convert PNG and JPEG images to WebP.

Disable PNG crunching

You only need this when you are building for release.

android {
  ...
  aaptOptions {
    cruncherEnabled false
  }
}

Enable Instant Run

Open the Settings or Preferences dialog.
Navigate to Build, Execution, Deployment > Instant Run.
Make sure Enable Instant Run is checked.

Using ProGuard

Go to Gradle and add this..

buildTypes {
        debug {
            debuggable true
            minifyEnabled false
        }
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

If you are getting any error, then do a clean rebuild of the project.
You can add rules in the proguard file like this.

	-dontwarn com.squareup.okhttp.**

Accelerate Clean Builds with Build Cache

Your clean builds are much faster while using the cache because the build system can simply reuse those cached files during subsequent builds, instead of recreating them. The build cache also works on continuous integration servers and when running multiple build processes on a single local machine.

android {
  defaultConfig {
    // If you do enable multidex, you must also set
    // minSdkVersion to 21 or higher.
    multiDexEnabled false
  }
  buildTypes {
    <build-type> {
      minifyEnabled false
    }
  }
  dexOptions {
    preDexLibraries true
  }
  ...
}

Enable Daemon and Parallel Build

You can specify the below two lines in the gradle-wrapper.properties

# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
org.gradle.parallel=true
# When set to true the Gradle daemon is used to run the build. For local developer builds this is our favorite property.
# The developer environment is optimized for speed and feedback so we nearly always run Gradle jobs with the daemon.
org.gradle.daemon=true

Using the daemon will make your builds startup faster as it won’t have to start up the entire Gradle application every time. You can read more about this from here.
https://docs.gradle.org/current/userguide/gradle_daemon.html.

The parallel builds setting could be unsafe for some projects. The requirement is that all your modules must be decoupled or your build could fail (see http://gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects for details).

Enable Incremental build

Add this option to your android block:

dexOptions {
    incremental true
}

In that dexOptions block you can also specify the heap size for the dex process, for example:

dexOptions {
    incremental true
    javaMaxHeapSize "12g"
}

Build APK from terminal faster

To build,install and uninstall an apk from terminal.
Its usually faster than building from android studio.

$ ./gradlew assembleDebug
$ ./gradlew installDebug
$ ./gradlew uninstallAll

Leave a Reply

Your email address will not be published. Required fields are marked *