Your Gradle Build Is Redoing Work It Already Did

A measured walk through the configuration cache, the build cache, and the module structure that keeps both honest.
Most slow Android builds are not slow because Gradle is slow. They are slow because Gradle is asked, again and again, to re-derive answers it already computed: the same task graph, the same compiled classes, the same generated sources. Three features exist to stop that waste: the configuration cache, the build cache, and a well-shaped module graph. Turning on the two caches takes one line each; the module graph is design work. Keeping all three working is the actual job.
1. Profile with Build Analyzer
The profiling loop: baseline, open analyzer, read the report, change one thing, re-measure
Get a baseline you can trust
A single stopwatch run on a warm laptop is noise. Use gradle-profiler so every scenario gets warm-ups, repeated iterations and a median. A scenario file for the three situations that matter day to day:
# perf.scenarios clean_assemble { tasks = [":app:assembleDebug"] cleanup-tasks = ["clean"] warm-ups = 2 iterations = 5 } leaf_edit { tasks = [":app:assembleDebug"] apply-non-abi-change-to = "feature/cart/src/main/kotlin/com/acme/shop/cart/CartViewModel.kt" warm-ups = 2 iterations = 5 } api_edit { tasks = [":app:assembleDebug"] apply-abi-change-to = "core/model/src/main/kotlin/com/acme/shop/model/Order.kt" warm-ups = 2 iterations = 5 } gradle-profiler --benchmark --scenario-file perf.scenarios clean_assemble leaf_edit api_edit Record the medians somewhere permanent. They are the “before” column you will be glad to have.
Read the report like a build engineer
Run a normal build in Android Studio, then open the Build tool window and select the Build Analyzer tab. Three views carry most of the value:
- Tasks determining build duration. This is the critical path: the chain of tasks that sets the wall-clock time. Making a task off the critical path faster changes nothing. Always start here.
- Plugins. The cumulative cost per plugin, which quickly exposes the one that adds seconds to every module.
- Warnings. Always-run tasks, non-incremental annotation processors, configuration cache problems, and heavy garbage collection (the usual sign that
org.gradle.jvmargsneeds a larger heap).
What the sample app’s report said, in order of pain:
- Configuration took about 14 seconds on a no-op build. Nothing had changed, yet Gradle re-ran every
build.gradle.kts. -
kaptGenerateStubsandkapttasks sat on the critical path of six modules. -
generateDebugBuildConfigre-ran on every build in three modules, with no source change to justify it.
Each finding maps to a section below. For a deeper, shareable view (including CI), add --scan and publish a build scan; --profile writes a lightweight HTML report to build/reports/profile if you can't publish anything.
Failure mode: profiling the wrong build. A report from a cold daemon includes JIT warm-up, dependency resolution and file-system cache fill. Profile the second or third build, and profile the scenario developers actually hit, not the one that makes the chart look best.
2. Fix cache misses
Two different caches, two different questions:
- The configuration cache asks: can I skip configuring the project, because nothing that configuration depends on has changed?
- The build cache asks: can I skip executing this task, because someone already ran it with identical inputs?
Start with the cheap one.
Configuration cache: turn it on, then make it stay on
# gradle.properties org.gradle.configuration-cache=true org.gradle.caching=true org.gradle.parallel=true org.gradle.jvmargs=-Xmx4g -XX:+UseParallelGC # While migrating, report problems instead of failing the build. # Remove this line once the report is clean. org.gradle.configuration-cache.problems=warn Configuration cache lifecycle: a cache hit replaces the configuration phase with a quick load
Gradle prints a link to an HTML problem report at the end of any build that violated the rules. The two offenders you will meet most often:
Failure mode 1: reaching for project inside a task action.
// Rejected by the configuration cache: Task.project is unavailable at execution time. tasks.register("printVersion") { doLast { println("Building ${project.version}") } } The task must carry everything it needs as serializable state. Capture the value during configuration:
tasks.register("printVersion") { val version = project.version.toString() doLast { println("Building $version") } } For anything beyond a throwaway task, declare a typed Property input (the cacheable task later in this section does exactly that).
Failure mode 2: a volatile value read during configuration. This one is quiet. The build works, but every CI run misses the cache.
// app/build.gradle.kts // Changes on every pipeline run, so the configuration cache can never be reused. android.defaultConfig { versionCode = System.getenv("CI_BUILD_NUMBER")?.toInt() ?: 1 } Gradle tracks environment variables read this way as inputs to the cache entry. A value that changes every build invalidates it every build. Keep pull-request and local builds on a constant, and inject the volatile value only on the pipeline that actually ships:
// app/build.gradle.kts (versionCode exists only on application modules) val isReleasePipeline = providers.gradleProperty("releasePipeline").isPresent android.defaultConfig { versionCode = if (isReleasePipeline) { // Fail loudly with a useful message instead of a bare NumberFormatException // when the variable is missing or empty. providers.environmentVariable("CI_BUILD_NUMBER").orNull?.toIntOrNull() ?: error("releasePipeline requires a numeric CI_BUILD_NUMBER") } else { 1 } } Also expect problems from older third-party plugins. Check each plugin’s release notes for configuration cache support before blaming your own scripts.
Build cache: understand the key, then protect it
A cache hit requires an identical cache key, which is a hash over every declared input of the task.
Anatomy of a build cache key: stable inputs produce a hit, unstable inputs force a re-execute
Verify it works with a clean build run twice:
./gradlew clean :app:assembleDebug ./gradlew clean :app:assembleDebug --console=plain | grep FROM-CACHE The second run should show FROM-CACHE on the expensive cacheable tasks, such as Kotlin and Java compilation. Not everything will: the Android Gradle Plugin deliberately leaves some cheap or I/O-bound steps (certain merge and packaging tasks) uncacheable, so judge the result by the slow tasks on your critical path, not by a 100% hit rate. Slow cacheable tasks that still re-execute are your investigation list. To see why, run the task with --info and compare the cache keys between two runs or two machines, or open a build scan comparison. -Dorg.gradle.caching.debug=true prints the individual input hashes when the key alone doesn't tell you enough.
Failure mode 3: a timestamp baked into BuildConfig.
android.defaultConfig { buildConfigField("long", "BUILT_AT", "${System.currentTimeMillis()}L") } This is a double bug. The generated class changes on every configuration, so generateDebugBuildConfig and everything compiled against it misses the cache. Worse, with the configuration cache on, the script doesn't even re-run, so the timestamp is frozen at whatever it was when the cache entry was stored, and the value in your app is silently wrong. Delete the constant and ask the platform at runtime:
fun Context.installedAtMillis(): Long { val info = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { packageManager.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(0)) } else { @Suppress("DEPRECATION") packageManager.getPackageInfo(packageName, 0) } return info.lastUpdateTime } (The two-argument getPackageInfo(String, Int) is deprecated from API 33, hence the guard.)
Failure mode 4: a custom task that isn’t cacheable, or is cacheable but sloppy. Here is a small task that generates a feature flag object from a properties file, written so that it caches correctly everywhere:
// build-logic/convention/src/main/kotlin/GenerateFeatureFlags.kt import org.gradle.api.DefaultTask import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.Property import org.gradle.api.tasks.CacheableTask import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.OutputDirectory import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.TaskAction import java.util.Properties @CacheableTask abstract class GenerateFeatureFlags : DefaultTask() { // RELATIVE: the same file at /Users/ana/... and /home/ci/... hashes identically. @get:InputFile @get:PathSensitive(PathSensitivity.RELATIVE) abstract val flagsFile: RegularFileProperty @get:Input abstract val packageName: Property<String> @get:OutputDirectory abstract val outputDir: DirectoryProperty @TaskAction fun generate() { val flags = Properties().apply { flagsFile.get().asFile.inputStream().use(::load) } // sorted(): Properties iteration order is not guaranteed, and unstable output // would change the inputs of every compile task downstream. // uppercase() is locale-invariant, so a Turkish-locale machine generates the same names. val body = flags.stringPropertyNames().sorted().joinToString("\n") { name -> " const val ${name.uppercase()} = ${flags.getProperty(name).toBoolean()}" } val pkg = packageName.get() val dir = outputDir.get().asFile.resolve(pkg.replace('.', '/')).also { it.mkdirs() } dir.resolve("FeatureFlags.kt").writeText( "package $pkg\n\nobject FeatureFlags {\n$body\n}\n" ) } } The three habits worth copying: declare every input with a type, use PathSensitivity.RELATIVE for files, and make output deterministic. Wire it into the variant's sources with the lazy API so it never runs unless something needs it:
// feature-flags/build.gradle.kts val generateFlags = tasks.register<GenerateFeatureFlags>("generateFeatureFlags") { flagsFile.set(layout.projectDirectory.file("flags.properties")) packageName.set("com.acme.shop.flags") outputDir.set(layout.buildDirectory.dir("generated/flags")) } androidComponents { onVariants { variant -> variant.sources.kotlin?.addGeneratedSourceDirectory( generateFlags, GenerateFeatureFlags::outputDir, ) } } Failure mode 5: the cache works on your laptop and nowhere else. Cross-machine hits die for boring reasons: a different JDK, a different absolute path baked into an input, a different locale. Pin the JDK with a toolchain (shown in the next section) so the compiler is the same everywhere, and treat any task showing absolute paths in its --info inputs as a bug.
Failure mode 6: a poisoned remote cache. A remote cache shared by everyone is only as trustworthy as its least careful writer. Let CI populate it and give developers read-only access:
// settings.gradle.kts buildCache { local { isEnabled = true } remote<HttpBuildCache> { url = uri("https://build-cache.example.com/cache/") isPush = providers.environmentVariable("CI").isPresent credentials { username = providers.environmentVariable("CACHE_USER").orNull password = providers.environmentVariable("CACHE_PASSWORD").orNull } } } Finally, take the annotation-processor warning seriously. If Build Analyzer flags kapt on the critical path, migrating Room, Hilt or Moshi to KSP typically removes a stub-generation step per module and gives you processors designed for incremental builds.
3. Convention plugins
Every fix above is a build logic fix: a toolchain, a flag, a compiler option. If each of 38 modules carries its own copy, the fixes drift. One module keeps an old jvmTarget, another sets a different compileSdk, and the cache hit rate quietly erodes because inputs no longer match.
Convention plugins: shared build logic in one included build instead of repeated in every module
The layout
The files involved, relative to the repository root:
-
settings.gradle.ktsregisters the included build. -
gradle/libs.versions.tomlis the shared version catalog. -
build-logic/settings.gradle.ktspoints the included build at that catalog. -
build-logic/convention/build.gradle.ktsdeclares the plugins. -
build-logic/convention/src/main/kotlin/holdsAndroidLibraryConventionPlugin.kt,AndroidFeatureConventionPlugin.ktandGenerateFeatureFlags.kt.
Register the included build as a source of plugins:
// settings.gradle.kts pluginManagement { includeBuild("build-logic") repositories { google() mavenCentral() gradlePluginPortal() } } Let build-logic read the same version catalog as the rest of the build:
// build-logic/settings.gradle.kts dependencyResolutionManagement { repositories { google() mavenCentral() gradlePluginPortal() } versionCatalogs { create("libs") { from(files("../gradle/libs.versions.toml")) } } } rootProject.name = "build-logic" include(":convention") # gradle/libs.versions.toml (excerpt) [versions] agp = "<your AGP version>" kotlin = "<your Kotlin version>" compileSdk = "35" minSdk = "26" [libraries] android-gradlePlugin = { module = "com.android.tools.build:gradle", version.ref = "agp" } kotlin-gradlePlugin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin" } // build-logic/convention/build.gradle.kts plugins { `kotlin-dsl` } kotlin { jvmToolchain(17) } dependencies { compileOnly(libs.android.gradlePlugin) compileOnly(libs.kotlin.gradlePlugin) } gradlePlugin { plugins { register("androidLibrary") { id = "acme.android.library" implementationClass = "AndroidLibraryConventionPlugin" } register("androidFeature") { id = "acme.android.feature" implementationClass = "AndroidFeatureConventionPlugin" } } } The plugins
// build-logic/convention/src/main/kotlin/AndroidLibraryConventionPlugin.kt import com.android.build.api.dsl.LibraryExtension import org.gradle.api.JavaVersion import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.artifacts.VersionCatalog import org.gradle.api.artifacts.VersionCatalogsExtension import org.gradle.kotlin.dsl.configure import org.gradle.kotlin.dsl.getByType import org.jetbrains.kotlin.gradle.dsl.KotlinAndroidProjectExtension internal val Project.libs: VersionCatalog get() = extensions.getByType<VersionCatalogsExtension>().named("libs") internal fun VersionCatalog.intVersion(alias: String): Int = findVersion(alias).get().requiredVersion.toInt() class AndroidLibraryConventionPlugin : Plugin<Project> { override fun apply(target: Project): Unit = with(target) { pluginManager.apply("com.android.library") pluginManager.apply("org.jetbrains.kotlin.android") extensions.configure<LibraryExtension> { compileSdk = libs.intVersion("compileSdk") defaultConfig.minSdk = libs.intVersion("minSdk") compileOptions { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } } extensions.configure<KotlinAndroidProjectExtension> { jvmToolchain(17) // one JDK everywhere keeps cache keys portable compilerOptions { allWarningsAsErrors.set( providers.gradleProperty("warningsAsErrors").map(String::toBoolean).orElse(false) ) } } } } If your Android Gradle Plugin version bundles Kotlin support itself, remove only the
pluginManager.apply("org.jetbrains.kotlin.android")line. Keep the Kotlin compiler settings (toolchain,compilerOptions), and check your AGP release notes for whichkotlinextension type they now configure. Convention plugins turn this kind of migration into a one-file change instead of 38.
A feature plugin builds on the library plugin and encodes the architectural rule: features depend on core modules, never on each other.
// build-logic/convention/src/main/kotlin/AndroidFeatureConventionPlugin.kt import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.dependencies class AndroidFeatureConventionPlugin : Plugin<Project> { override fun apply(target: Project): Unit = with(target) { pluginManager.apply("acme.android.library") dependencies { add("implementation", project(":core:model")) add("implementation", project(":core:ui")) } } } And a consuming module shrinks to what is actually unique about it:
// feature/cart/build.gradle.kts plugins { id("acme.android.feature") } android { namespace = "com.acme.shop.feature.cart" } Why this belongs in a build speed post
Convention plugins are not just tidiness. They are what keeps cache inputs identical across modules, and they give you one place to apply a speed fix to the whole build. Two more things make the module graph itself fast:
- Keep the graph wide and shallow. Gradle parallelizes across modules, so a few deep chains serialize the build. A rule like “features never depend on features” gives you dozens of independent compile tasks that can run side by side.
- Keep the public surface of core modules small. A change to a public signature recompiles every dependent module...
原文:https://www.a8q9.cn/en/article/your-gradle-build-is-redoing-work-it-already-did-e1e4f1.html


