How R8 made Kotlin Coroutines on Android 2x faster
Posted by Andrei Shikov, Senior Software Engineer, Android Toolkit and Jonathan Starup, Software Engineer, R8 Team Starting from AGP 9.2.0, R8 optimizes most Atomic*FieldUpdater calls into Unsafe variants that perform 2x to 4x better on common operations . This has a particularly large impact on the kotlinx.atomicfu library that implements atomics for kotlinx.coroutines , making launching and…
In Android 9.2.0 and later, R8 optimizes most Atomic*FieldUpdater calls, improving performance by up to 2x to 4x on common operations. This optimization significantly impacts the kotlinx.atomicfu library, which is utilized by kotlinx.coroutines to improve launching and cancelling coroutines. Consequently, this results in a 2x faster execution of coroutines on Android.
Kotlinx.coroutines, a standard for asynchronous programming, is widely adopted in Android apps, making coroutines a crucial component of Jetpack Compose. However, Compose's concurrent APIs, which heavily utilize coroutines for managing pointer events, animations, and other interactions, were found to be a performance bottleneck. As a result, much of the early performance work focused on minimizing coroutines from the default path and delaying initialization until necessary.
To analyze a function's internal behavior on Android, developers can use an Android Runtime (ART) method trace. For an empty LaunchedEffect { } call, the method trace reveals three key parts: initializing a new coroutine, starting the coroutine, and completing the coroutine. Cancelling LaunchedEffect is similar to normal completion, except it also creates a CancellationException.
However, frequent calls to java.util.concurrent.AtomicReferenceFieldUpdater (purple or green boxes with j… labels) were observed in the profiler. While each call is relatively fast, the frequency is concerning. Most of the time spent in these calls is due to reflection checks, which significantly impact performance. To address this issue, developers should update their Android Gradle Plugin (AGP) to 9.2.0 or above to benefit from R8's optimization.
Written by urgent.news from Android Developers Blog's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.