Gradle build slow on transformClassesWithDexForDebug

GradleAndroid Build

Gradle Problem Overview


Building my Android app takes about 90 seconds ("fast"), up to 3 minutes for each update to my code. It's a complete waste of time as it really and I assume a solution must be within reach. I tried investigating the issue and found different blog-posts and SO answers with suggestions, most of which I've tried.

  • I have the gradle.properties file with org.gradle.deamon=true
  • I run on Android Studio with Gradle Prefence to do offline work (improved, but still slow)
  • I run on command line (which is faster, but still slow)
  • In build.gradle, defaultConfig, I have multiDexEnabled set to false
  • In build.gradle, dexOptions, I have preDexLibraries set to false
  • In gradle-wrapper.properties I fetch a recent gradle version (2.8) (the significant speed changes happened on 2.4)

The process that seems to take long, about 85% of total build time is :app:transformClassesWithDexForDebug

What is that process actually doing? I can find people who have crashes on it, but it works fine for me, except for the fact that it takes a lot of time. And do I need it, since I don't really need Dex at this point?

Also, I have 13 dependencies and 3 testCompile dependencies. I already point to specific play packages, so I'm not compiling stuff I don't need. If I understand things correctly, gradle is building all those libraries each project build as well. If that is correct, is there a way to skip that? Can I build them myself as wrapped-up libraries and include them without the need for them to be processed each time? That might make me lose some flexibility for future changes to dependencies, but at this point I feel like I'm losing over an hour a day easily on waiting for gradle. I'm not sure if flexibility is worth that much to me.

I'm looking forward to get any pointers on how I can improve my build process. Thank you in advance.

Gradle Solutions


Solution 1 - Gradle

Edit: At this point, I recommend running Android Studio 2.x side by side with your 1.5 installation. You get access to instant-run, which really helps as well as all the updated tools. If you are staying on 1.5 read on...

I have managed to speed up Android Studio 1.5 debug builds from 2 minutes to 30 seconds. This might not work with your command-line execution, but might be faster.

Using this config, your first IDE build takes the same amount of time, but Incremental builds are faster, even if you modify classes. You lose some gain if you modify attached libraries.

Step 1. (If you're fortunate enough to target minSdkVersion of >= 21 already, skip this.)

@vanomart 's answer of having a minSdkVersion debug flavour of >= 21 is not wrong, but the only part necessary is adding the following to module (app) build.gradle and ensuring you target dev while debugging in your Build Variants tab:

android {
    [...]
    productFlavors {
        dev {
            minSdkVersion 21 //The important bit.
        }
        prod {
            minSdkVersion 15 //Example. Set to your real requirement.
        }
    }

Step 2. Pre-dexing libs.

In your module (app) build.gradle set the following config. This is faster for IDE builds, not so much for builder-servers who start from scratch every build.

android {
    [...]
    dexOptions {
        preDexLibraries true
        javaMaxHeapSize "2g" // Use gig increments depending on needs
    }

Source, doing (partly) inverse of "Improving Build Server performance": http://tools.android.com/tech-docs/new-build-system/tips#TOC-Improving-Build-Server-performance

Step 3. Make sure you're using latest buildToolsVersion in module (app) build.gradle.

android {
    buildToolsVersion "23.0.2"
    [...]

> "... update the build tools version in all your modules to the latest > (23.0.2). [...] it will use a new faster version of dex, which helps > both instant run and a full build be a bit faster."

Source: http://tools.android.com/tech-docs/instant-run

Step 4. Use latest Gradle build tools

In your project build.gradle, set to latest (currently 2.0.0-alpha6)

buildscript {
    dependencies {
        classpath 'com.android.tools.build:gradle:2.0.0-alpha6'

Updates list: http://tools.android.com/tech-docs/new-build-system

Step 5. Use latest Gradle wrapper. Modify gradle-wrapper.properties, update this line to use 2.10:

distributionUrl=https\://downloads.gradle.org/distributions/gradle-2.10-all.zip
#Alternative url if the above does not work:
#distributionUrl=https://services.gradle.org/distributions/gradle-2.10-all.zip

In Android Studio preferences, ensure you have "Use default Gradle wrapper" selected. I recommend restarting Android Studio to ensure the Gradle daemon restarts.

> "In many cases, Gradle 2.9 is much faster than Gradle 2.8 when > performing incremental builds."

Source: docs.gradle.org/current/release-notes

Solution 2 - Gradle

Upgrading to Android Studio 2.1 and the Android Gradle Plugin v2.1.0 has largely fixed this problem for me. After installing the updated IDE, you should be prompted to update your Gradle plugin as well. You'll know you have the right version if your root build.gradle file has the following line:

classpath 'com.android.tools.build:gradle:2.1.0'

IMPORTANT: In addition to upgrading, you also need to increase the amount of memory allocated to the Gradle daemon to 2048mb, so it can perform this expensive dex-ing step in process. To do so, add the following to your root gradle.properties file:

org.gradle.jvmargs = -Xmx2048m

I had similarly slow build times as experienced in the question above, but after upgrading my build speeds increased dramatically. See the release notes for the Android Gradle Plugin v2.1.0 here for more info:

http://developer.android.com/tools/revisions/gradle-plugin.html

Solution 3 - Gradle

Only solution that worked for me was to disable instant run.

Android Studio -> Preferences -> Build, Execution, Deployment -> Instant Run -> Uncheck 'Enable instant run [...]'

Build went from over 2 minutes to 40 seconds.

Solution 4 - Gradle

I was facing the same issue and it took me around 10 hours to finally resolve it, so I know your feels.

I googled a lot, I did the same configuration stuff as you did and even if it helped a little, the compiling and running the actual app was still pain in the ass (sometimes it took 2-3 minutes when I changed one line of code, but when I did more work, it usually took 8 minutes and my computer was totally frozen during that time).

But enough talks, lets fix this. What 'app:transformClassesWithDexForDebug' does is that it resolves some dependencies for Dalvik (pre-5.0, api 21) OS versions and what is important - it takes a lot of time. You won't need it for developing, because you can test your app on >= 21, so create separate product flavor for development and release. Here is my gradle build that makes use of it:

apply plugin: 'com.android.application'

final VERSION_MAJOR = 0
final VERSION_MINOR = 0
final VERSION_PATCH = 0
final VERSION_BUILD = 1

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.app"
        minSdkVersion 15
        targetSdkVersion 23
        multiDexEnabled true
        versionName "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}.${VERSION_BUILD}"
        versionCode VERSION_MAJOR * 10000000 + VERSION_MINOR * 100000 + VERSION_PATCH * 1000 + VERSION_BUILD
    }

    dexOptions {
        incremental = true;
        preDexLibraries = false
        javaMaxHeapSize "2g"
    }


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

    productFlavors {
        dev {
            minSdkVersion 21
            applicationId = "com.app.test"
        }
        prod {
            minSdkVersion 15
            applicationId = "com.app" // you don't need it, but can be useful

        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LGPL2.1'
        exclude 'META-INF/ASL2.0'
    }
    lintOptions {
        checkReleaseBuilds false
        abortOnError true
    }

}

afterEvaluate {
    tasks.matching {
        it.name.startsWith('dex')
    }.each { dx ->
        if (dx.additionalParameters == null) {
            dx.additionalParameters = ['--multi-dex']
        } else {
            dx.additionalParameters += '--multi-dex'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
   ... 
}

Next thing is to make sure you are actually building your app with this build variant. Click on View -> Tool Windows -> Build tools and make sure you have build variant set to 'devDebug'

For some people this might be enough. I found a lot of threads here in SO and also on reddit that ended with this product flavor thing, but this didn't help me at all actually. What helped me is to uprade gradle manually. Since you already tried to do it, I think you are on the right track, but I would suggest using newer gradle version 2.9 which has '40% improved performance' over 2.8.

Solution 5 - Gradle

That seems like part of the new Instant Run mechanism introduced in Android Studio 2.0 preview, which is responsible to instrument every methods in your app to create execution branch for future code patch. I'm afraid that's why it is extremely slow.

It's weird this task is still taking place even if Instant Run is disabled. I have to downgrade "com.android.tools.build:gradle" to 1.3.0 to avoid that task.

Solution 6 - Gradle

Does your application have a database? Does the DB have a big size?

If yes:

  • remove the DB from assets folder (or wherever you keep it) and do a build
  • measure the difference in build times
  • IN MY CASE: it was a dramatic difference from 45 sec down to 15 sec

If No:

  • Monitor Gradle console during incremental builds and see what operation is taking the most time

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJustin HammengaView Question on Stackoverflow
Solution 1 - Gradledyson returnsView Answer on Stackoverflow
Solution 2 - Gradlemarkdb314View Answer on Stackoverflow
Solution 3 - GradleEnaView Answer on Stackoverflow
Solution 4 - GradlevanomartView Answer on Stackoverflow
Solution 5 - GradleOasis FengView Answer on Stackoverflow
Solution 6 - GradleAlexVPerlView Answer on Stackoverflow