Managing Gradle builds for large projects requires a focus on simplicity and performance. As a project grows to hundreds or thousands of modules, build complexity and resource consumption (CPU, memory, and I/O) increase significantly.
This guide provides best practices for managing large Android builds, focusing on reducing complexity and optimizing build speed. It can be helpful to read this guide sequentially. The code snippets can be seen in the context of this sample project.
1. Enable performance-enhancing Gradle properties
Gradle has many performance-enhancing features that require build teams to opt in, because some of these features require a strictness with the build that Gradle itself doesn't enforce. Each of these properties is explained in more detail in the subsections that follow.
Performance-enhancing features in the gradle.properties file:
# Set JVM args
org.gradle.jvmargs=-Xmx8g -XX:MaxMetaspaceSize=1g -Dfile.encoding=UTF-8 -XX:+HeapDumpOnOutOfMemoryError
# Enable the build cache
org.gradle.caching=true
# Parallel task execution
org.gradle.parallel=true
# Parallel model building for IDE sync
org.gradle.tooling.parallel=true
# Configuration Cache
org.gradle.configuration-cache=true
org.gradle.configuration-cache.parallel=true
# Consider adding this for ephemeral CI builds
org.gradle.configuration-cache.read-only=true
# Isolated Projects
# Gradle <9.7
org.gradle.unsafe.isolated-projects=true
# Gradle 9.7+
org.gradle.isolated-projects=true
Set the arguments passed to the VM running your build
The org.gradle.jvmargs property controls the JVM running the build. It
defaults to -Xmx512m "-XX:MaxMetaspaceSize=384m". See
Configuring Gradle for details.
org.gradle.jvmargs=-Xmx8g -XX:MaxMetaspaceSize=1g -Dfile.encoding=UTF-8 -XX:+HeapDumpOnOutOfMemoryError
The exact value to use for the -Xmx portion of the argument will vary by the
size of your build. Generally, pick the smallest value necessary to enable your
build to complete while spending less than 5% of total build duration in garbage
collection.
Setting -XX:MaxMetaspaceSize=1g caps the maximum metaspace size at 1 GB.
Because setting org.gradle.jvmargs replaces the default JVM arguments rather
than appending to them, set both -Xmx and -XX:MaxMetaspaceSize. For more
information, see Gradle issue #19750.
Setting -Dfile.encoding=UTF-8 ensures that the file encoding is consistent
regardless of the environment in which the build is run.
Setting -XX:+HeapDumpOnOutOfMemoryError will cause a heap dump to be generated
if your build fails with an OutOfMemoryError. Such heap dumps can be analyzed
to determine if there are memory leaks in your build.
Enable the build cache
Enable the build cache. See Build Cache for details.
org.gradle.caching=true
A build of any size will benefit from the build cache.
Enable parallel task execution
Enable parallel execution. See Enable Parallel Execution for details.
org.gradle.parallel=true
Gradle, by default, only runs one task at a time. Enabling parallel execution lets Gradle run tasks from independent projects in parallel, significantly improving build performance.
Enable parallel Tooling API actions
Enable parallel Tooling API actions. See Configure Tooling API actions parallelism for details.
org.gradle.tooling.parallel=true
Enabling parallel execution also enables parallel Tooling API actions, which can improve the performance of scenarios like IDE sync.
Enable the configuration cache
Enable the configuration cache. See Enabling and Configuring the Configuration Cache for details.
org.gradle.configuration-cache=true
Enabling the configuration cache significantly improves build performance by allowing Gradle to cache the results of the configuration phase.
Enable parallel configuration caching
Enable parallel configuration caching. See Enable Parallel Configuration Caching for details.
org.gradle.configuration-cache.parallel=true
By default, storing and loading of the configuration cache happens serially. Enabling parallel caching can improve build performance.
Consider setting the configuration cache to read-only on CI
Consider setting the configuration cache to read-only on Continuous Integration (CI). See Making the Configuration Cache Read-Only for details.
org.gradle.configuration-cache.read-only=true
In an ephemeral CI environment, it can be more performant to make the configuration cache read-only. In such environments, it is a waste of time to serialize the configuration cache to disk, since it will be deleted when the build completes.
Enable isolated projects
Enable isolated projects. See Isolated Projects for details.
org.gradle.isolated-projects=true
Enabling isolated projects turns on two features: parallel project configuration and finer-grained caching of configuration results. This can significantly improve build performance.
2. Share build logic with convention plugins
As stated in Gradle's best practices guide, you should use convention plugins to avoid duplicating configuration across build scripts. Furthermore, we recommend using what Gradle calls "typed binary" plugins instead of precompiled script plugins.
You can think of convention plugins as wrappers around ecosystem plugins which
apply common conventions to a build. Ecosystem plugins are plugins like the
com.android.application plugin, the java-library, or the
org.jetbrains.kotlin.jvm plugins. They're designed to solve the general
problem of how to build Android apps, or Java or Kotlin libraries. Convention
plugins make that abstract problem more concrete by solving how your team
builds its software. This is a simpler problem because you're solving it for
just your team, instead of every team in the world in the case of an ecosystem
plugin.
Binary plugins are preferred for large builds because they are easier to structure for complex use cases. They improve maintainability, simplify debugging, and are easier to test.
Configure your main build
First, wire the main build to the build-logic build, which is in a subdirectory
in the same repository. Use the following code in the settings.gradle.kts
file:
pluginManagement {
includeBuild("build-logic")
}
Put the includeBuild method call inside the pluginManagement block to
enable use of Settings plugins, which is important when you
centralize class loading.
Configure build-logic
Next, configure the build-logic/conventions module, which will contain all of
the convention plugins.
The build-logic/conventions/build.gradle.kts file:
plugins {
id("java-gradle-plugin")
alias(libs.plugins.kotlin.jvm)
alias(libs.plugins.android.lint)
}
gradlePlugin {
plugins {
register("com.example.android-app") {
implementationClass = "com.example.AndroidAppConventionPlugin"
}
register("com.example.android-lib") {
implementationClass = "com.example.AndroidLibConventionPlugin"
}
}
}
dependencies {
implementation(libs.agp)
lintChecks(libs.androidx.lint.gradle)
}
This build script does the following:
- Applies the
Gradle Plugin Development
Plugin
(
java-gradle-plugin), and the Kotlin-JVM plugin (org.jetbrains.kotlin.jvm) so that the plugin's implementation language can be Kotlin. - Applies the Android Lint plugin (
com.android.lint) and adds theandroidx-lint-gradledependency, which ensures your build-logic doesn't violate any best practices. - Configures the
gradlePluginblock for two plugins, one for Android app modules and the other for Android library modules. - Adds a dependency on the Android Gradle plugin (the ecosystem plugin) so you can configure it with your team's conventions.
Write the Android app convention plugin
With the build wiring taken care of, you can write your convention plugins. Here's an example of an Android application convention plugin.
The
build-logic/conventions/src/main/kotlin/com/example/AndroidAppConventionPlugin.kt
file:
package com.example
public abstract class AndroidAppConventionPlugin : Plugin<Project> {
override public fun apply(target: Project): Unit = target.run {
pluginManager.apply("com.android.application")
BasePlugin(this).apply()
configureAndroidDsl()
}
private fun Project.configureAndroidDsl() {
extensions.configure(ApplicationExtension::class.java) { android ->
android.run {
CommonConfiguration(android).configure()
defaultConfig {
targetSdk = 36
}
}
}
}
}
This plugin applies the base (ecosystem) com.android.application plugin, and
configures it. It also applies our BasePlugin (see below for details). Some of
the configuration is particular to Android applications, while other parts of it
share features with Android libraries. Such common configuration should be
extracted to a helper class to eliminate duplication and keep your code
maintainable.
Write the Android library convention plugin
Here's an example of an Android library convention plugin in the
build-logic/conventions/src/main/kotlin/com/example/AndroidLibConventionPlugin.kt
file:
package com.example
public abstract class AndroidLibConventionPlugin : Plugin<Project> {
override public fun apply(target: Project): Unit = target.run {
pluginManager.apply("com.android.library")
BasePlugin(this).apply()
configureAndroidDsl()
}
private fun Project.configureAndroidDsl() {
// If project.path is ":core:utils", this becomes "com.example.core.utils"
val libNamespace = "com.example${path.replace(':', '.')}"
extensions.configure(LibraryExtension::class.java) { android ->
android.run {
CommonConfiguration(android).configure()
namespace = libNamespace
defaultConfig {
consumerProguardFiles("consumer-rules.pro")
}
}
}
}
}
This plugin applies the base (ecosystem) com.android.library plugin, and
configures it. Like the Android application convention plugin, it applies our
BasePlugin. Similarly to the Android application convention plugin, some of
the configuration is specific to Android libraries, while other parts are
shared in common with Android applications.
Write the CommonConfiguration helper class
Here's an example of a helper class that handles configuration common to both
Android applications and Android libraries, in the
build-logic/conventions/src/main/kotlin/com/example/internal/CommonConfiguration.kt
file:
package com.example.internal
internal class CommonConfiguration(
private val commonExtension: CommonExtension,
) {
fun configure(): Unit = commonExtension.run {
compileSdk {
version = release(36) {
minorApiLevel = 1
}
}
defaultConfig.run {
minSdk = 24
}
compileOptions.run {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
}
}
The helper class usually grows over time, as build requirements grow and change.
Write the BasePlugin class
As with CommonConfiguration (which is specific to Android modules), it's
common for convention plugins to have global configuration that applies to all
module types, including Android, JVM, etc. You can manage this using a
BasePlugin class, which you create and apply in all of your top-level
conventions. Note that it doesn't have to be—even shouldn't be—a Gradle plugin.
A simple Kotlin class is sufficient.
internal class BasePlugin(private val project: Project) {
fun apply(): Unit = project.run {
// … configuration common to all modules in your project …
}
}
This class can have many potential functions, including:
- Applying and configuring other third-party plugins
- Registering a task you need to be available globally
- Creating extensions
- Adding dependencies
You can think of this as "configuration inversion," where instead of
trying to apply global configuration from a single global location (such as in
the root build script with unsafe APIs like allprojects or subprojects), you
do the configuration in each module individually, but managed globally with your
convention plugins. This follows Gradle's design philosophy, where each module
is considered an isolated unit. Note that allprojects and subprojects are
considered unsafe not only because they violate the Isolated Projects
contract, but also introduce coupling between modules in your build. These
relationships are ad hoc and unmodeled, which can lead to inconsistencies in
your build results.
Use the new convention plugins in your main build
Apply the convention plugin to your Android application and library module.
In the app/build.gradle.kts file:
plugins {
id("com.example.android-app")
}
In the library/build.gradle.kts file:
plugins {
id("com.example.android-lib")
}
With the new convention plugins, your build scripts might not need to configure
the android block at all, which makes them simple and maintainable.
3. Centralize class loading, and simplify settings scripts, with a settings convention plugin
Depending on the structure of your main build, build dependencies (plugins and their dependencies) can be loaded in multiple classloaders. This complexity can lead to class visibility issues and build failures that are difficult to debug. Using a settings convention plugin eliminates this problem by centralizing class loading in a single class loader in the settings context.
Configure your main build
First, wire your main build to your build-logic build. Additionally, apply the new settings convention plugin directly to the settings script.
In the settings.gradle.kts file:
pluginManagement {
includeBuild("build-logic")
}
plugins {
id("com.example.settings")
}
Configure build-logic
Next, configure the build-logic/conventions module, which contains all of the
convention plugins.
In the build-logic/conventions/build.gradle.kts file:
plugins {
id("java-gradle-plugin")
alias(libs.plugins.kotlin.jvm)
}
gradlePlugin {
plugins {
register("com.example.settings") {
implementationClass = "com.example.SettingsConventionPlugin"
}
}
}
dependencies {
implementation(libs.agp)
implementation(libs.foojay)
}
Write the settings convention plugin
With the build wiring taken care of, you can write your settings convention plugin. Here's an example.
In the
build-logic/conventions/src/main/kotlin/com/example/SettingsConventionPlugin.kt
file:
package com.example
public abstract class SettingsConventionPlugin : Plugin<Settings> {
override public fun apply(target: Settings): Unit = target.run {
pluginManager.apply("org.gradle.toolchains.foojay-resolver-convention")
dependencyResolutionManagement.run {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories.run {
google()
mavenCentral()
}
}
}
}
This settings convention plugin serves two purposes:
- As noted earlier, it centralizes the build classpath by ensuring all build
dependencies are loaded in a single class loader. This happens because:
- The
build-logic/conventionsmodule declares dependencies on all required plugins, such as AGP and Foojay; and - This module is loaded in the settings context when the plugin is applied to the settings script.
- The
- The second purpose is to configure the settings script. Doing this provides similar advantages as do convention plugins for build scripts.
4. Write functional tests for custom build logic
Don't rely only on manual verification to test your build. Treat build logic as application code that requires a test suite to ensure reliability and prevent regressions.
Automated tests help verify that the build configuration remains correct as the project evolves, protecting against changes that could disrupt development.
Because many Gradle plugin tasks rely on the Gradle API and are difficult to
unit test using helper classes like ProjectBuilder, use functional testing
instead. See
Writing a functional test
for an example. There are also community plugins that make this easier.
5. Use Kotlin/Java JVM modules for non-Android business logic
Separate Android modules from JVM modules because Android modules have more overhead. Use Android modules only when Android-specific features, such as resources or packaging, are required.
Encapsulate business logic in JVM modules to improve build speed and simplify testing.
Note that Android modules can depend on JVM modules, but JVM modules cannot depend on Android modules. Maintaining this dependency structure is key to keeping builds fast.
As a simple demonstration of why this practice can be so effective, consider the following example:
In the lib/src/main/kotlin/com/example/RealService.kt file:
package com.example
class RealService {
// …
}
This Kotlin code could be packaged as either a Kotlin/JVM module or an Android library module.
In the Kotlin/JVM case:
./gradlew :lib:build --console=verbose
> Task :lib:checkKotlinGradlePluginConfigurationErrors SKIPPED
> Task :lib:processTestResources NO-SOURCE
> Task :lib:processResources NO-SOURCE
…
If you count the number of tasks in this build, there should be 15 or so.
And in the Android case:
./gradlew :lib:build --console=verbose
> Task :lib:generateDebugAssets UP-TO-DATE
> Task :lib:preBuild UP-TO-DATE
> Task :lib:prepareLintJarForPublish
…
And if you count the number of tasks in this case, there should be 93 or so, which is much more.
6. Apply plugins selectively to minimize overhead
Apply plugins only where they are needed to avoid unnecessary configuration overhead.
Instead of applying plugins globally, use one of the following approaches to apply them selectively:
- Direct application: Apply the plugin directly to the build scripts that require it.
- Feature plugins: Wrap the plugin and its configuration in a convention plugin, and apply that plugin to the modules that need it.
- Custom DSL: Expose toggles in a custom extension to let developers opt in to specific features.
Examples of each approach are presented in the following sections.
Apply the optional plugin directly
Applying the plugin directly is the most straightforward approach, but if you need to add configuration for this optional plugin in each module, it can become verbose.
In the lib/build.gradle.kts file:
plugins {
id("com.example.android-lib")
id("com.optional.plugin")
}
// other configuration for this plugin
Apply the optional plugin using a specialized convention plugin
With this approach, you encapsulate all configuration in a new convention plugin.
In the build-logic/conventions/build.gradle.kts file:
dependencies {
implementation(libs.optional.plugin)
}
Every time you want to apply a plugin using your build-logic, you need to make that plugin's implementation available through a dependency declaration.
In the
build-logic/conventions/src/main/kotlin/com/example/OptionalConventionPlugin.kt
file:
package com.example
abstract class OptionalConventionPlugin : Plugin<Project> {
override fun apply(target: Project): Unit = target.run {
pluginManager.apply("com.optional.plugin")
// other configuration for this plugin
}
}
In the lib/build.gradle.kts file:
plugins {
id("com.example.android-lib")
id("com.example.optional-plugin")
}
Apply the optional plugin using a custom DSL
With this final approach, the logic for applying and configuring the optional plugin remains encapsulated in your build logic, but you expose it using a custom DSL instead of providing it through a separate convention plugin.
In the build-logic/conventions/build.gradle.kts file:
dependencies {
implementation(libs.optional.plugin)
}
Every time you want to apply a plugin using your build-logic, you need to make that plugin's implementation available through a dependency declaration.
In the
build-logic/conventions/src/main/kotlin/com/example/extension/BestPracticesExtension.kt
file:
package com.example.extension
public abstract class BestPracticesExtension @Inject constructor(
private val project: Project,
) {
private val optionalPluginEnabled = project.objects.property(Boolean::class.java)
fun enableOptionalPlugin() {
optionalPluginEnabled.lock()
project.pluginManager.apply("com.example.optional-plugin")
// other configuration for this plugin
}
/** Ensure we only configure this value once. */
private fun Property<Boolean>.lock() {
set(true)
disallowChanges()
}
internal companion object {
fun create(project: Project): BestPracticesExtension {
return project.extensions.create(
"bestPractices",
BestPracticesExtension::class.java,
project,
)
}
}
}
The new extension, which will be exposed to build scripts as the bestPractices
block, can apply plugins and do any other configuration that a Plugin<Project>
implementation class can.
In the
build-logic/conventions/src/main/kotlin/com/example/AndroidLibConventionPlugin.kt
file:
package com.example
public abstract class AndroidLibConventionPlugin : Plugin<Project> {
override public fun apply(target: Project): Unit = target.run {
pluginManager.apply("com.android.library")
BestPracticesExtension.create(this)
}
}
Create the extension with the convention plugin so that Gradle can make it available to build scripts.
In the lib/build.gradle.kts file:
plugins {
id("com.example.android-lib")
}
bestPractices {
enableOptionalPlugin()
}
Finally, use the new extension to opt in to various features.
7. Keep the application module minimal
Keep any Android application modules minimal, with as little source code as
possible. Ideally, they should only contain an Application subclass
responsible for initializing the dependency injection graph.
Minimal app modules enable easier modularization across the whole build, which can dramatically improve build performance due to parallelization, finer-grained build cache entries, and more.
Below is an example using Hilt for dependency injection.
Configure your app module
First, apply your convention plugin, which will also handle adding any other necessary plugins (such as Hilt and KSP), as well as boilerplate dependencies.
In the app/build.gradle.kts file:
plugins {
id("com.example.android-app")
}
dependencies {
// …
}
The dependencies block will contain declarations for the other modules in your project.
Write your custom Application subclass
Since Hilt requires the @HiltAndroidApp annotation to be in an Android
application module, the custom Application class can't be placed anywhere else.
The sole purpose of this class is to instantiate the object graph and inject any
global services, such as the hypothetical AnalyticsService below.
In the app/src/main/kotlin/com/example/app/ExampleApp.kt file:
package com.example.app
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
import javax.inject.Inject
@HiltAndroidApp
class ExampleApp : Application() {
@Inject
lateinit var analyticsService: AnalyticsService
override fun onCreate() {
super.onCreate()
analyticsService.analyze()
}
}
8. Don't use product flavors
To simplify the build and improve IDE performance, avoid using product flavors. Product flavors can slow down IDE sync and make refactoring difficult because the IDE only indexes the active variant.
Instead of product flavors, create separate modules for different targets.
File structure:
├── app-common
│ ├── build.gradle.kts
│ └── src
│ └── main
│ └── kotlin
│ └── com
│ └── example
│ └── BaseApp.kt
├── app-fire
│ ├── build.gradle.kts
│ └── src
│ └── main
│ └── kotlin
│ └── com
│ └── example
│ └── FireApp.kt
└── app-water
├── build.gradle.kts
└── src
└── main
└── kotlin
└── com
└── example
└── WaterApp.kt
In the app-common/build.gradle.kts file:
plugins {
id("com.example.android-lib")
}
In the app-fire/build.gradle.kts file:
plugins {
id("com.example.android-app")
}
android {
defaultConfig {
applicationId = "com.example.fire"
}
}
dependencies {
implementation(project(":app-common"))
}
In the app-water/build.gradle.kts file:
plugins {
id("com.example.android-app")
}
android {
defaultConfig {
applicationId = "com.example.water"
}
}
dependencies {
implementation(project(":app-common"))
}
With this structure, you can build the fire "flavor" with ./gradlew
:app-fire:assemble and the water "flavor" with ./gradlew :app-water:assemble.
9. Disable the debug build type in library modules
Android library modules usually don't require separate debug and release build types. Disabling the debug build type in libraries improves build and sync performance, and ensures developers test the same configuration that is shipped.
Note: In rare cases, it can be useful to make use of the debug/release concept for library modules. For example, you might have resources or other assets that are build type-specific. But this should be used sparingly.
Configure the Android library convention plugin
First, configure your Android library convention plugin to switch the tested build type from the default value of "debug" to "release", and then disable the debug build type.
In the
build-logic/conventions/src/main/kotlin/com/example/AndroidLibConventionPlugin.kt
file:
package com.example
abstract class AndroidLibConventionPlugin : Plugin<Project> {
override fun apply(target: Project): Unit = target.run {
pluginManager.apply("com.android.library")
extensions.configure(LibraryExtension::class.java) { android ->
with(android) {
...
testBuildType = "release"
...
}
}
extensions.configure(LibraryAndroidComponentsExtension::class.java) {
androidComponents ->
val selector = androidComponents.selector().withBuildType("debug")
androidComponents.beforeVariants(selector) { builder -> builder.enable = false }
}
}
}
Unit tests can now be run with:
./gradlew :lib:test
Similarly, Android (device) tests can be run with:
./gradlew :lib:connectedAndroidTest
Set matchingFallbacks in application modules
Update the Android app convention plugin to configure its debug build type to have a matching fallback of "release".
In the
build-logic/conventions/src/main/kotlin/com/example/AndroidAppConventionPlugin.kt
file:
package com.example
abstract class AndroidAppConventionPlugin : Plugin<Project> {
override fun apply(target: Project): Unit = target.run {
pluginManager.apply("com.android.application")
extensions.configure(ApplicationExtension::class.java) { android ->
with(android) {
...
buildTypes {
...
debug {
matchingFallbacks += "release"
}
}
}
}
}
}
10. Avoid experimental type-safe project accessors
Avoid using Gradle's experimental type-safe project accessors. While they enable IDE auto-complete for project dependencies, they can cause build script recompilation issues when projects are added, removed, or renamed.
11. Automate dependency updates
Use automated tools like Renovate to keep dependencies up to date. Renovate supports version catalogs, lockfiles, and the Gradle wrapper, and can be configured to manage dependency updates automatically.
References to third-party tools are for illustrative purposes only. Google does not endorse specific package manager solutions, and alternative tools are available to developers.
12. Run benchmarks regularly with Gradle Profiler
Use Gradle Profiler to benchmark build performance and detect regressions. You can configure scenarios to run benchmarks on a regular schedule and track results over time.
Create a scenarios file
The benchmark.scenarios file:
// Simulates first build of the day after pulling
cleanBuild {
tasks = [":app:assembleDebug"]
cleanup-tasks = ["clean"]
}
// Simulates building after a change deep in the dependency hierarchy
abiChange {
tasks = [":app:assembleDebug"]
apply-abi-change-to = "utils/src/main/kotlin/com/example/utils/UtilUsedEverywhere.kt"
}
// Allows tracking of configuration time when there is a configuration cache hit
configurationCache {
tasks = [":app:assembleDebug"]
gradle-args = ["--dry-run"]
}
// Allows tracking of configuration time when there is a configuration cache miss
noConfigurationCache {
tasks = [":app:assembleDebug"]
gradle-args = ["--dry-run", "--no-configuration-cache"]
}
Gradle Profiler is versatile, so see the documentation for ideas on the many ways a scenarios file can be configured.
The ide-benchmark.scenarios file:
// Allows tracking IDE sync performance
// When running this scenario, the following additional steps are necessary:
// 1. Ensure Android Studio is installed with a known path.
// 2. For a cloud (CI) environment
// export GRADLE_PROFILER_OPTS="$GRADLE_PROFILER_OPTS -Dstudio.tests.headless=true"
// 3. Add this argument to the invocation: `--studio-install-dir <studio install dir>`
ideSync {
android-studio-sync {
studio-jvm-args = ["-Xmx16g"]
}
}
It's good practice to separate the IDE sync scenarios since they require additional setup, particularly in a CI environment.
Run gradle-profiler with your scenarios files
Build benchmarks:
gradle-profiler --benchmark --project-dir . --scenario-file benchmark.scenarios
IDE sync benchmarks:
export GRADLE_PROFILER_OPTS="$GRADLE_PROFILER_OPTS -Dstudio.tests.headless=true"
gradle-profiler --benchmark --project-dir . --scenario-file ide-benchmark.scenarios --studio-install-dir <studio install dir>
Gradle Profiler will create an HTML report you can review, as well as a CSV report you can parse yourself for custom analysis.
13. Profile to find hot spots
If build performance regresses, use profiling to identify bottlenecks. You can
use Gradle Profiler or use Java Flight Recorder (JFR) through the jcmd tool to
generate profile data that can be analyzed in IntelliJ or elsewhere.
When profiling, it's important to be specific. Rather than running
./gradlew build, narrow your search down to a specific Gradle task that seems
slow.
With the jcmd tool
To profile using the jcmd tool, first identify the PID of the Gradle Daemon
process you want to profile. One way to do this is with jps.
Use jps to identify the PID of the Gradle Daemon process:
jps
88610 Jps
77510 GradleDaemon
64409
77208 GradleDaemon
18873 Main
77870 KotlinCompileDaemon
24687 MainWrapper
There are often multiple daemon processes running concurrently. If you're
unsure which is the one you want, kill all of them and start a new build, at
which point you should see only a single GradleDaemon process.
It helps to have two terminals for the next part.
Start jcmd:
jcmd <pid> JFR.start filename=dump.jfr
In one terminal, start jcmd.
Run the slow task:
./gradlew :path:to:slowTask
In another terminal, run the slow task.
Once the task completes, go back to the first terminal and stop jcmd.
Stop jcmd:
jcmd <pid> JFR.stop
Finally, navigate to the JFR file that jcmd has created and drag it into your
IDE.
Conclusion
These best practices will reduce your build's complexity, improve its performance, and improve its maintainability. While teams of any size can benefit from these practices, teams responsible for large projects can expect to see the most benefits.
Additional resources
- Optimize your build speed
- Troubleshoot build performance with Build Analyzer
- Configure build variants
- Apply custom build logic