用户回答:https://stackoverflow.com/users/624706/sergii-pechenizkyi
来源:Building and running app via Gradle and Android Studio is slower than via Eclipse
硬件
很抱歉,将开发站升级到 SSD 和大量内存的影响可能比以下几点加起来还要大。
工具版本
提高构建性能是开发团队的首要任务,因此请确保您使用的是最新的 Gradle 和 Android Gradle Plugin。
配置文件
在任何适用的目录中创建一个名为 gradle.properties 的文件:
-
/home/<username>/.gradle/ (Linux)
-
/Users/<username>/.gradle/ (Mac)
-
C:\Users\<username>\.gradle (Windows)
追加:
# 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 属性放置在 projectRoot\gradle.properties,则它们在本地工作,如果您将它们放置在 user_home\.gradle\gradle.properties,则全局工作。如果您从控制台或直接从想法运行 gradle 任务,则应用属性:
IDE 设置
可以从 IDE 设置 GUI 调整 Gradle-IntelliJ 集成。启用“离线工作”(检查下面yava 的答案)将禁用每个“同步 gradle 文件”上的真实网络请求。
原生多索引
apk 构建最慢的步骤之一是将 java 字节码转换为单个 dex 文件。启用本机 multidex(minSdk 21 仅用于调试构建)将有助于工具减少工作量(查看下面Aksel Willgert 的答案)。
依赖关系
首选@aar 依赖于库子项目。
在 mavenCentral、jCenter 上搜索 aar 包或使用 jitpack.io 从 github 构建任何库。如果您不编辑依赖库的源代码,则不应每次都使用项目源代码构建它。
防病毒
考虑从防病毒扫描中排除项目和缓存文件。这显然是与安全性的权衡(不要在家里尝试这个!)。但是如果你在分支之间切换很多,那么杀毒软件会在允许 gradle 进程使用它之前重新扫描文件,这会减慢构建时间(特别是 AndroidStudio 同步项目与 gradle 文件和索引任务)。在启用和不启用防病毒软件的情况下测量构建时间和进程 CPU 以查看是否相关。
分析构建
Gradle 内置了对profiling projects 的支持。不同的项目使用插件和自定义脚本的不同组合。使用--profile 将有助于找到瓶颈。