[android] Building and running app via Gradle and Android Studio is slower than via Eclipse

I have a multi-project (~10 modules) of which building takes about 20-30 seconds each time. When I press Run in Android Studio, I have to wait every time to rebuild the app, which is extremely slow.

Is it possible to automate building process in Android Studio? Or do you have any advice on how to make this process faster?

In Eclipse, thanks to automatic building, running the same project on an emulator takes about 3-5 seconds.

This is my build.gradle file (app module):

buildscript {
    repositories {
        maven { url 'http://repo1.maven.org/maven2' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.4'
    }
}
apply plugin: 'android'

dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
    compile project(':libraries:SharedLibs')
    compile project(':libraries:actionbarsherlock')
    compile project(':libraries:FacebookSDK')
    compile project(':libraries:GooglePlayServices')
    compile project(':libraries:HorizontalGridView')
    compile project(':libraries:ImageViewTouch')
    compile project(':libraries:SlidingMenu')
}

android {
    compileSdkVersion 17
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 16
    }
}

This question is related to android gradle android-studio build.gradle

The answer is


Update After Android Studio 2.3

All answers are great, and I encourage to use those methods with this one to improve build speed.

After release of android 2.2 on September 2016, Android released experimental build cache feature to speed up gradle build performance, which is now official from Android Studio 2.3 Canary. (Official Release note)

It introduces a new build cache feature, which is enable by default, can speed up build times (including full builds, incremental builds, and instant run) by storing and reusing files/directories that were created in previous builds of the same or different Android project.

How to use:

Add following line in your gradle.properties file

android.enableBuildCache = true
# Set to true or false to enable or disable the build cache. If this parameter is not set, the build cache is enable by default.

Clean the cache:

  • There is a new Gradle task called cleanBuildCache for you to more easily clean the build cache. You can use it by typing the following in your terminal:

    ./gradlew cleanBuildCache

  • OR You can clean the cache for Android studio 2.2 by deleting all the files store at location

    C:\Users\<username>\.android\build-cache


Solved mine with

File -> Settings -> Build, Execution, Deployment -> Build Tools -> Gradle -> Offline work

Gradle builds went from 8 minutes to 3 seconds.


This setup goes really fast for me (about 2 seconds the build)

build.gradle

android {

    dexOptions {
        incremental true
        preDexLibraries = false
        jumboMode = false
        maxProcessCount 4
        javaMaxHeapSize "6g"
    }
}

gradle.properties

org.gradle.daemon=true
org.gradle.parallel=true
org.gradle.jvmargs=-Xmx8192M

my PC:

  • CPU Intel(R) Pentium(R) CPU G2030 @ 3.00GHz, 3000 Mhz, 2 procesadores principales, 2 procesadores lógicos
  • x64
  • Microsoft Windows 7 Professional
  • (RAM) 16,0 GB

project files
- All located in local HD


In our specific case, the problem was due to having the retrolambda plugin, which forced all projects and subprojects to recompile everytime we tried to launch our application, even if no code had been altered in our core modules.

Removing retrolamba fixed it for us. Hope it helps someone.


I'm far from being an expert on Gradle but my environment had the following line in .gradle/init.gradle

gradle.projectsLoaded {
    rootProject.allprojects {
        repositories {
            mavenRepo name: 'libs-repo', url: 'http://guest-vm/artifactory/repo'
        }
    }
}

Yet I have no idea why that line was there, but I try changing to

gradle.projectsLoaded {
    rootProject.allprojects {
        repositories {
            mavenCentral()
        }
    }
} 

and now I finally can work without swearing to Android Studio & Gradle buildind scheme.


Just try this first. It is my personal experience.

I had the same problem. What i had done is just permanently disable the antivirus (Mine was Avast Security 2015). Just after disabling the antivirus , thing gone well. the gradle finished successfully. From now within seconds the gradle is finishing ( Only taking 5-10 secs).


If anyone is working a project which is synced via Subversion and this still happening, I think this can slow the process of workflow in Android Studio. For example if it work very slow while: scrolling in a class,xml etc, while my app is still running on my device.

  • Go to Version Control at Preferences, and set from Subversion to None.enter image description here

USE this sudo dpkg --add-architecture i386 sudo apt-get update sudo apt-get install libncurses5:i386 libstdc++6:i386 zlib1g:i386

Android Studio fails to build new project, timed out while wating for slave aapt process


Just another performance imporvement tip:

Android Studio 3.0 includes new DEX compiler called D8.

"The dex compiler mostly works under the hood in your day-to-day app development, but it directly impacts your app's build time, .dex file size, and runtime performance."

"And when comparing the new D8 compiler with the current DX compiler, D8 compiles faster and outputs smaller .dex files, while having the same or better app runtime performance."

D8 is optional - do use it we have to put to project's gradle.properties

android.enableD8=true

More informations: https://android-developers.googleblog.com/2017/08/next-generation-dex-compiler-now-in.html

PS. It impove my build time by about 30%.


According to the android documentation, add this in the gradle file of app module.

android {
    ...
    dexOptions {
    preDexLibraries true
    maxProcessCount 8
    }
}

You can ignore gradle update-to-date checks.

enter image description here

For Windows running Android Studio 1.5: Go to File -> Settings -> Build, Execution, Deployment -> Build tools -> Gradle -> Check Offline work (as shown in image)

down from ~30+ sec to ~3 sec


Hi I know this is very very late answer but maybe help someone
in my case I was using

compile 'com.android.support:support-v4:23.1.1'

in my app Gradle dependency
but in one of my libraries it was

 compile 'com.android.support:support-v4:23.0.1'

after change all to latest version my problem solved.


The accepted answer is for older versions of android studio and most of them works still now. Updating android studio made it a little bit faster. Don't bother to specify heap size as it'll increase automatically with the increase of Xms and Xmx. Here's some modification with the VMoptions

  1. In bin folder there's a studio.vmoptions file to set the environment configuration. In my case this is studio64.vmoptions Add the following lines if they're not added already and save the file. In my case I've 8GB RAM.

    -Xms4096m
    -Xmx4096m
    -XX:MaxPermSize=2048m
    -XX:+CMSClassUnloadingEnabled
    -XX:+CMSPermGenSweepingEnabled 
    -XX:+HeapDumpOnOutOfMemoryError
    -Dfile.encoding=utf-8`
    
  2. Start android studio. Go to File-> Settings-> Build, Execution, Deployment-> Compiler

    • Check compile independent modules in parallel
    • In command-line Options write: --offline
    • Check Make project automatically
    • Check configure on demand

In case of using mac, at first I couldn't find the vmoptions. Anyway, here's a nice article about how we can change the vmoptions in MAC OSX. Quoting from this article here.

Open your terminal and put this command to open the vmoptions in MAC OSX:

open -e /Applications/Android\ Studio.app/Contents/bin/studio.vmoptions

Here's what helped this beginning Android programmer (former professional programmer, years ago) in speeding up Android Studio 2.2. I know this is a rehash, but, just summarizing in one place.

Initial builds can still be brutally slow, but restarts of running apps are now usually very tolerable. I'm using a sub-optimal PC: AMD Quad-Core A8-7410 CPU, 8MB RAM, non-SSD HD, Win 10. (And, this is my first Stack Overflow posting.... ;)

IN SETTINGS -> GRADLE:

yes for "Offline work" (this is perhaps the most import setting).

IN SETTINGS -> COMPILER:

yes for "Compile independent modules in parallel" (not sure if this does in fact help utilize multicore CPUs).

IN GRADLE SCRIPTS, "build.gradle (Module: app)":

defaultConfig {
    ...
   // keep min high so that restarted apps can be hotswapped...obviously, this is hugely faster.
   minSdkVersion 14
   ...
    // enabling multidex support...does make big difference for me.
    multiDexEnabled true

ALSO IN GRADLE SCRIPTS, "gradle.properties (Project Properties)":

org.gradle.jvmargs=-Xmx3048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

org.gradle.parallel=true org.gradle.daemon=true

Additionally, testing on a physical device instead of the emulator is working well for me; a small tablet that stands up is convenient.


After change this settings my compile duration 10 minutes changed to ~10 secs.

Step 1:

Settings(ctrl+Alt+S) ->

Build,Execution,Deployment ->

Compiler ->

type "--offline" in command-line Options box.

Step 2:

check the “Compile independent modules in parallel” checkbox.

& click Apply -> OK

enter image description here

Reference - https://www.sundoginteractive.com/blog/speed-up-gradle-in-android-studio

Disadvantage:

You will not be able to pull down the latest versions of the dependencies identified in your build.gradle file. It runs faster because it uses a cached snapshot of those imported libraries.

Important Note: When you deploy the application remove this settings & build with latest versions of dependencies.


Following the steps will make it 10 times faster and reduce build time 90%

First create a file named gradle.properties in the following directory:

/home/<username>/.gradle/ (Linux)
/Users/<username>/.gradle/ (Mac)
C:\Users\<username>\.gradle (Windows)

Add this line to the file:

org.gradle.daemon=true
org.gradle.parallel=true

And check this options in Android Studio

enter image description here


You could try opening the gradle menu on the right side of studio, and assemble only the modules you have changed, then run the install command. When you press run it assembles everything regardless of any changes you you may have made to the code it is assembling


Searched everywhere for this and finally found a solution that works for us. Enabling parallel builds (On OSX: preferences -> compiler -> gradle -> "Compile independent modules in parallel") and enabling 'make project automatically' brought it down from ~1 min to ~20 sec. Thanks to /u/Covalence.

http://www.reddit.com/r/androiddev/comments/1k3nb3/gradle_and_android_studio_way_slower_to_build/


If using google play services, depending on just the libraries you need instead of the whole blob can make things faster.

If your only need is maps, use:

compile 'com.google.android.gms:play-services-maps:6.5.+'

instead of:

compile 'com.google.android.gms:play-services:6.5.+'

The latter brings 20k methods (see blog) into the classpath, which might tip the total method count over 64k.

That would force the use of proguard or multidex even for debug builds. For one of my projects i had the following build times

  • multidex build (with supportlibrary) ~40sec
  • proguard build ~20sec
  • build when method limit < 64k ~5sec

If developing on sdk 21+, it would possible to optimize multidex builds as stated in the android documentation

android {
    productFlavors {
        // Define separate dev and prod product flavors.
        dev {
            // dev utilizes minSDKVersion = 21 to allow the Android gradle plugin
            // to pre-dex each module and produce an APK that can be tested on
            // Android Lollipop without time consuming dex merging processes.
            minSdkVersion 21
        }
        prod {
            // The actual minSdkVersion for the application.
            minSdkVersion 14
        }
    }
    ...
}

Speed Up Gradle Build In Android Studio 3.2.1

Ever feel like you are waiting for the builds to complete in Android Studio for minutes? Me too. And it’s a pretty annoying. Fortunately, there are a few ways that you can use to improve this. Android uses Gradle for building. The latest version is 4.6 has a huge performance boost over previous versions (see Release notes for details).

Step 1: Update Gradle version An easier way to accomplish this is to go to: Open Module Settings (your project) > Project Structure

enter image description here

UPDATE

Change to Gradle version: 4.6 and Change to Android Plugin Version: 3.2.1

enter image description here

Download Gradle Release distributive from https://services.gradle.org/distributions/gradle-4.6-all.zip And copy it to the Gradle folder:

enter image description here

Last step is to add your discribution in Settings > Gradle

enter image description here

Don’t forget to click Apply to save changes.

Step 2: Enable Offline mode, Gradle daemon and parallel build for the project Offline mode tells Gradle to ignore update-to-date checks. Gradle asks for dependencies everytime and having this option makes it just uses what is already on the machine for dependencies. Go to Gradle from android studio Setting and click in Offline work box.

enter image description here

  1. Go to Compiler from android studio Setting and add “— offline” in command-line box and click Compile independent modules in parallel.

enter image description here

The next step is to enable the Gradle daemon and parallel build for your project. Parallel builds will cause your projects with multiple modules (multi-project builds in Gradle) to be built in parallel, which should make large or modular projects build faster.

enter image description here

These settings could enabled by modifiing a file named gradle.properties in Gradle scripts directory(i.e., ~/.gradle/gradle.properties).Some of these options (e.g. Complie modules in parallel) are available from Android Studio and also enabled there by default, but putting them in the gradle.properties file will enabled them when building from the terminal and also making sure that your colleagues will use the same settings. But if you’re working on a team, sometimes you can’t commit this stuff.

# 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. The Gradle Daemon is not enabled by default, but it’s recommend always enabling it for developers’ machines (but leaving it disabled for continuous integration servers). FAQ about this mode could be found 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).

Step 3: Enable incremental dexign and tweak memory settings You can speed up your builds by turning on incremental dexing. In your module’s build file:

enter image description here

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"
}

Where “12g” is 12GB of memory. Additional information about this could be found here google.github.io/android-gradle-dsl/current/ You can also configure Gradle parameters in the settings file, e.g. increase the max heap size in case you have a large project:

# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

See all list of parameters here: https://docs.gradle.org/current/userguide/userguide_single.html#sec:gradle_configuration_properties for details.

Step 4: Disable Antivirus Consider to exclude project and cache files from antivirus scanning. This is obviously a trade off with security. But if you switch between branches a lot, then antivirus will rescan files before allowing gradle process to use it, which slows build time (in particular Android Studio sync project with gradle files and indexing tasks). Measure build time and process CPU with and without antivirus enabled to see if it is related. I hope this helps. Leave a comment if you have any question or some other tips for improving the build performance.

helpful link


A trivial change (to a resoruce xml) still took 10 minutes. As @rivare says in his answer, a command line build is mutch faster (took this down to 15 seconds).
Here are some steps to at least make a trivial build fast from the command line for Windows.

  1. Go to your projects root (where the gradlew.bat is):

    cd c:\android\MaskActivity

  2. execute the build:

    gradlew assembleDebug

  3. uninstall the apk from the phone directly (drag it to uninstall).

  4. When the build is finished, kill the BIG java process using Windows Task Manager.

OR if you have unix tools on your Windows machine:

ps

"pid" 's are shown:

kill -9 <pid>
  1. Now install your apk:

    adb -d install C:\Android\MaskActivity\app\build\outputs\apk\app-debug.apk


I recently bought a new SSD and went from Windows to Linux.My build times are now an order of magnitude faster, and no longer annoying.

Though it does not directly answer your question as to why it's slower than eclipse, it shows that the process is disk-bounded and an upgrade to an SSD might be a (somewhat expensive) solution. I'm guessing there will be people googling the issue and ending up here, who might appreciate my experience.


Just create a file named gradle.properties in the following directory:

/home/<username>/.gradle/ (Linux)
/Users/<username>/.gradle/ (Mac)
C:\Users\<username>\.gradle (Windows)

Add this line to the file:

org.gradle.daemon=true

For me the speed is now equal to Eclipse.

Source: https://www.timroes.de/2013/09/12/speed-up-gradle/


I was fed up with the slow build of android on my local machine. The way I solved this was spinning up a high-end machine on AWS and rsyncing the code from my local to the machine and compiling it over there.

I saw an immediate increase in the performance and my local system was saved from CPU hog. Check out this tool I created to help the developers speed up their terminal https://stormyapp.com


To run Android envirorment on low configuration machine.

  1. Close the uncessesory web tabs in browser
  2. For Antivirus users, exclude the build folder which is auto generated
  3. Android studio have 1.2 Gb default heap can decrease to 512 MB Help > Edit custom VM options studio.vmoptions -Xmx512m Layouts performace will be speed up

  4. For Gradle one of the core component in Android studio Mkae sure like right now 3.0beta is latest one

Below tips can affect the code quality so please use with cautions:

  1. Studio contain Power safe Mode when turned on it will close background operations that lint , code complelitions and so on.

  2. You can run manually lintcheck when needed ./gradlew lint

  3. Most of are using Android emulators on average it consume 2 GB RAM so if possible use actual Android device these will reduce your resource load on your computer. Alternatively you can reduce the RAM of the emulator and it will automatically reduce the virtual memory consumption on your computer. you can find this in virtual device configuration and advance setting.

  4. Gradle offline mode is a feature for bandwidth limited users to disable the downloading of build dependencies. It will reduce the background operation that will help to increase the performance of Android studio.

  5. Android studio offers an optimization to compile multiple modules in parallel. On low RAM machines this feature will likely have a negative impact on the performance. You can disable it in the compiler settings dialog.


Please follow the following steps.

  1. Enable offline mode : Please check below print screen.

    https://i.stack.imgur.com/RF9uG.png

  2. Enable Instant Run : Please check below print screen.

    https://i.stack.imgur.com/mvHKJ.png

    If you want to learn more about instant run please visit android developer site.


You could make the process faster, if you use gradle from command line. There is a lot of optimization to do for the IDE developers. But it is just an early version.

For more information read this discussion on g+ with some of the devs.


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to gradle

Gradle - Move a folder from ABC to XYZ A failure occurred while executing com.android.build.gradle.internal.tasks Gradle: Could not determine java version from '11.0.2' Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0 Failed to resolve: com.android.support:appcompat-v7:28.0 Failed to resolve: com.google.firebase:firebase-core:16.0.1 com.google.android.gms:play-services-measurement-base is being requested by various other libraries java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

Examples related to android-studio

A failure occurred while executing com.android.build.gradle.internal.tasks "Failed to install the following Android SDK packages as some licences have not been accepted" error Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util This version of Android Studio cannot open this project, please retry with Android Studio 3.4 or newer WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()' Flutter plugin not installed error;. When running flutter doctor ADB.exe is obsolete and has serious performance problems Android design support library for API 28 (P) not working Flutter command not found How to find the path of Flutter SDK

Examples related to build.gradle

Android Material and appcompat Manifest merger failed Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve Android dependency has different version for the compile and runtime Setting up Gradle for api 26 (Android) What's the difference between implementation and compile in Gradle? More than one file was found with OS independent path 'META-INF/LICENSE' Android Studio - Failed to notify project evaluation listener error Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2 All com.android.support libraries must use the exact same version specification DELETE_FAILED_INTERNAL_ERROR Error while Installing APK