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
}
}
Hardware
I'm sorry, but upgrading development station to SSD and tons of ram has probably a bigger influence than points below combined.
Tools versions
Increasing build performance has major priority for the development teams, so make sure you are using latest Gradle and Android Gradle Plugin.
Configuration File
Create a file named gradle.properties
in whatever directory applies:
/home/
/Users/
C:\Users\
Append:
# IDE (e.g. Android Studio) users:
# Settings specified in this file will override any Gradle settings
# configured through the IDE.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# The Gradle daemon aims to improve the startup and execution time of Gradle.
# When set to true the Gradle daemon is to run the build.
# TODO: disable daemon on CI, since builds should be clean and reliable on servers
org.gradle.daemon=true
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# https://medium.com/google-developers/faster-android-studio-builds-with-dex-in-process-5988ed8aa37e#.krd1mm27v
org.gradle.jvmargs=-Xmx5120m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
org.gradle.parallel=true
# Enables new incubating mode that makes Gradle selective when configuring projects.
# Only relevant projects are configured which results in faster builds for large multi-projects.
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:configuration_on_demand
org.gradle.configureondemand=true
# Set to true or false to enable or disable the build cache.
# If this parameter is not set, the build cache is disabled by default.
# http://tools.android.com/tech-docs/build-cache
android.enableBuildCache=true
Gradle properties works local if you place them at projectRoot\gradle.properties
and globally if you place them at user_home\.gradle\gradle.properties
. Properties applied if you run gradle tasks from console or directly from idea:
IDE Settings
It is possible to tweak Gradle-IntelliJ integration from the IDE settings GUI. Enabling "offline work" (check answer from yava below) will disable real network requests on every "sync gradle file".
https://i.stack.imgur.com/hGnDg.png
Native multi-dex
One of the slowest steps of the apk build is converting java bytecode into single dex file. Enabling native multidex (minSdk 21 for debug builds only) will help the tooling to reduce an amount of work (check answer from Aksel Willgert below).
Dependencies
Prefer @aar
dependencies over library sub-projects.
Search aar package on mavenCentral, jCenter or use jitpack.io to build any library from github. If you are not editing sources of the dependency library you should not build it every time with your project sources.
Antivirus
Consider to exclude project and cache files from antivirus scanning. This is obviously a trade off with security (don't try this at home!). 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 AndroidStudio 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.
Profiling a build
Gradle has built-in support for profiling projects. Different projects are using a different combination of plugins and custom scripts. Using --profile
will help to find bottlenecks.
You can ignore gradle update-to-date checks.
https://i.stack.imgur.com/wrwgo.png
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
gradle
is run. That's bizarre.
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/
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.
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
https://i.stack.imgur.com/xFm0I.png
UPDATE
Change to Gradle version: 4.6 and Change to Android Plugin Version: 3.2.1
https://i.stack.imgur.com/2hNtg.png
Download Gradle Release distributive from https://services.gradle.org/distributions/gradle-4.6-all.zip And copy it to the Gradle folder:
https://i.stack.imgur.com/DNm1e.png
Last step is to add your discribution in Settings > Gradle
https://i.stack.imgur.com/jOrQL.png
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.
https://i.stack.imgur.com/2HeBg.png
Go to Compiler from android studio Setting and add “— offline” in command-line box and click Compile independent modules in parallel.
https://i.stack.imgur.com/W9cgJ.png
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.
https://i.stack.imgur.com/Vhps7.png
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:
https://i.stack.imgur.com/eWQwO.png
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.
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
}
}
...
}
play-service
library, I compiled only maps
and locations
and disabled the multidex
. I feel the big difference. Thanks +1
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
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` 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
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/
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.
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.
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\
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
https://i.stack.imgur.com/gjRRV.png
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.
Solved mine with
File -> Settings -> Build, Execution, Deployment -> Build Tools -> Gradle -> Offline work
Gradle builds went from 8 minutes to 3 seconds.
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.
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%.
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
Please follow the following steps.
Enable offline mode : Please check below print screen. https://i.stack.imgur.com/RF9uG.png 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 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
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.
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.
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).
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.
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
https://i.stack.imgur.com/1y4t4.png
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
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.
Go to your projects root (where the gradlew.bat is): cd c:\android\MaskActivity execute the build: gradlew assembleDebug uninstall the apk from the phone directly (drag it to uninstall). 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>
Now install your apk: adb -d install C:\Android\MaskActivity\app\build\outputs\apk\app-debug.apk
According to the android documentation, add this in the gradle file of app module.
android {
...
dexOptions {
preDexLibraries true
maxProcessCount 8
}
}
To run Android envirorment on low configuration machine.
Close the uncessesory web tabs in browser For Antivirus users, exclude the build folder which is auto generated 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 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:
Studio contain Power safe Mode when turned on it will close background operations that lint , code complelitions and so on. You can run manually lintcheck when needed ./gradlew lint 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. 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. 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.
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
Success story sharing
dependencies {compile 'com.android.support:support-v4:21.0.+'}
is a slow solution? not sure to understand