Limiting Android Studio Memory Use Using systemd-run ad-hoc CGroups
If you're developing Android apps using Android Studio, it's not uncommon for you to experience a sluggish overall system performance when Android Studio is doing its thing.
More specifically in my case, on my laptop with 24GB RAM, running a web browser along with Android Studio meant all kinds of weird behaviour – from frozen tabs to failed downloads and sluggish mouse movements – leading me to file frivolous bugs in browser forums. The root cause being Android Studio's memory consumption forcing my system to swap to my SSD and affecting disk performance.
One option is to set vm.swappiness
kernel parameter to 0
from the current sysctl vm.swappiness = 60
. This would also help extend the life of my SSD. But in general, I've never seen the swapfile being used on my system even with 50+ browser tabs open and VS Code running merrily. See here if this is an option for you.
Instead, I prefer limiting resources to the problematic memory-hungry apps.
Here's what works on my Linux Mint system using kernel CGroups:
systemd-run \
--user \
-p MemoryLimit=10G \
-p CPUShares=100 \
--unit=android-studio \
--slice=android-studio \
$PATH_TO/android-studio/bin/studio.sh
A transient systemd
unit file is automatically created with the following configuration:
Background
Limiting Android Studio's memory consumption through configuration is no easy task. Ideally, you'd want a single setting to govern the whole suite of internal tasks Android Studio runs to compile, assemble, deploy, emulate your app. But there's no escaping the myriad set of technologies at play – the JVM, Gradle daemon, Kotlin daemon, Emulator, the IDE itself and optionally IDE plugins like Github Copilot (if you're using it).
Although Android Studio makes an effort in helping you configure some of these memory settings, there's no holistic estimate of how much memory you're going to end up using for Android development.