Speed up your Android / Kmm builds
It happens to everyone. You are coding your project for months, even years, and after a while, you realize that build times are getting longer and longer. Eventually, it gets to a point where your focus breaks every time you need to re-build your project. This is especially true when dealing with bugs.
In my medium-size Kmm project, building and deploying could take between 30 to 60 seconds. Compose previews took anywhere from 20 to 30s to load. It was terrible.
Now, there are several ways we can speed up Gradle builds. For example, you can turn on Gradle’s configuration cache. If you have no unsupported Gradle plugins in your project, you could turn this feature on and shave off about 5 to 10 seconds occasionally, which is pretty good.
You could also try and separate your code into smaller modules. Since Gradle only recompiles modules that were modified, you could certainly save some time by splitting your code. Of course, this requires time to do and if your project is already pretty big, it could lead to long refactor times.
So eventually, I stumbled upon the Gradle compatibility page, and noticed Gradle’s compatibility chart with Java JDKs.
In my project, I am using the Gradle 7.5 wrapper, so I could use JDK version up to 18. I noticed, on my machine, that the JDK installed was actually version 11. I’ve been an android dev for a long time and let’s just say that I don’t have the habit to update my machine’s JDK 😅
Anyway, using Android Studio’s settings, I could see the Gradle JDK selector
You can use this dropdown to download a newer JDK. Since I was using Gradle 7.5, I decided to download JDK 18 using the GUI.
Just by making this change, builds became spectacularly fast. Adding new classes in the Kotlin common code and other bigger changes had compile times of around 10s. Smaller Compose UI changes took less than 5s. Compose previews take about 1 or 2s to load. This is wayyy better than my original numbers!
This is fun and all, but my Gradle CLI commands were still slow. In my different projects, I usually define a “checkCommon” task that does a ktlintCheck and runs all unit tests from the common code. This usually took around 4m30s to run all ~500 unit tests. So I set Corretto 18 as my JAVA_HOME on my machine and, lo and behold, it now takes between 15 to 30s to complete.
The moral of this story, do check Gradle version compatible JDK once in a while! And, of course, mileage may vary depending on your specific machine.