自從升級了Gradle 2.2.之后,發(fā)現(xiàn)打包速度明顯變慢。 WTF!
現(xiàn)在gradlew clean build大約要4分鐘才能完成,到底發(fā)生了什么事情呢?
1. 初現(xiàn)端倪
通過 gradlew build --profile 可以輸出打包過程的profile report。先看一下最初的Report文件:


發(fā)現(xiàn)有2個問題:
a. 每次build都會執(zhí)行l(wèi)int,而這個lint report目前來說對我們完全沒有用。
b. 我只是單純的想跑個Debug的build task,為何Release相關(guān)的Task也執(zhí)行了?
2. 禁用Lint
如果想禁用某個task可以直接
gradlew build -X lint -X lintVitalRelease
或者直接永久禁用lint:
在build.gradle 文件的
apply plugin: 'com.android.application'
之前添加以下代碼:
tasks.whenTaskAdded { task ->
if (task.name.contains("lint")) {
task.enabled = false
}
}
3. Debug or Release
經(jīng)過測試發(fā)現(xiàn)gradlew build這個task執(zhí)行時,不區(qū)分Debug\Release , 所有類型的task都會執(zhí)行。所以我們盡量使用以下命令:
//命令這么長,記得用簡寫哦
gradlew assembleDebug
gradlew assembleRelease
gradlew installDebug
gradlew installRelease
4. 還是慢啊
經(jīng)過測試,時間由3分45秒提升到1分45秒左右。但是為何還是這么慢!這個app:transformClassesWithDexForDebug是個什么鬼,這么慢。

經(jīng)過調(diào)研發(fā)現(xiàn)這個app:transformClassesWithDexForDebug是打dex文件的核心task,要讓它提高速度,我們需要做一下處理:
dexOptions {
preDexLibraries true
javaMaxHeapSize "2g"
}
順帶解決下這個提示的問題吧:

5. 最后的總結(jié)

呵呵,還只是比最開始快2分鐘多一點。這些profile都是clean后做的Build。修改之后病歷夾clean之后點擊運行一共需要一分半吧。

其實日常改代碼經(jīng)常是走的Incremental Build而非全量Build,因為gradle對Incremental Build有一些優(yōu)化,它的耗時從20秒到3分半鐘都有可能,要做測試相對困難一些,總體來說經(jīng)過以上的配置,速度還是快一些的~ 至于你信不信,試了就知道嘍....
6. gradle.properties 文件也show一下吧
# 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.
org.gradle.daemon=true
# 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=-Xmx2560m -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
7. 寫在刨坑之后
產(chǎn)品中使用了SonarQube做代碼質(zhì)量的監(jiān)控。直接禁用lint會導(dǎo)致SonarQube的異常。