54 lines
1.9 KiB
Plaintext

== Why is this an issue?
The logic of a task's actions, like `doFirst` and `doLast`, is only executed when the task is executed.
Configuration logic (everything outside the action blocks) is executed in the configuration phase for every build,
whether the task will be executed or not.
Code that could also be moved into the action blocks but resides in the configuration logic can
inflict a performance penalty.
=== What is the potential impact?
==== Performance
Moving code from the task's configuration logic into the task's action blocks can speed up your builds.
== How to fix it
Move variable declarations and initializations into action blocks if they are read-only inside the action blocks.
An exception is the read access to the project configurations,
which should only happen during the configuration phase because of the configuration cache.
=== Code examples
==== Noncompliant code example
[source,kotlin,diff-id=1,diff-type=noncompliant]
----
tasks.register("printArtifactNames") {
val libraryNames = configurations.compileClasspath.get().map { it.name } // Non-compliant: "map" is always executed, but the result used in actions only
doLast {
logger.quiet(libraryNames.joinToString())
}
}
----
==== Compliant solution
[source,kotlin,diff-id=1,diff-type=compliant]
----
tasks.register("printArtifactNames") {
val compileClasspath: FileCollection = configurations.compileClasspath.get()
doLast {
val libraryNames = compileClasspath.map { it.name } // Compliant: defined in action where it is used
logger.quiet(libraryNames.joinToString())
}
}
----
== Resources
=== Documentation
* https://docs.gradle.org/current/userguide/authoring_maintainable_build_scripts.html#sec:minimize_logic_executed_configuration_phase[Gradle Documentation: Minimize logic executed during the configuration phase]
* https://docs.gradle.org/current/userguide/configuration_cache.html[Gradle Documentation: Configuration cache]