Android Developers Blog
Follow
How R8 made Kotlin Coroutines on Android 2x faster
The Android team has been working on optimizing the performance of coroutines in Android apps, particularly those using Kotlin. The kotlinx.atomicfu library, which is used by kotlinx.coroutines, was found to be a bottleneck due to its use of AtomicReferenceFieldUpdater, which has a significant overhead due to reflection checks. To address this issue, the R8 compiler has been updated to optimize most AtomicFieldUpdater calls into Unsafe variants, resulting in a 2x to 4x performance improvement. This optimization is available in AGP 9.2.0 and later versions, and it has a significant impact on the performance of Jetpack Compose, which uses coroutines extensively. The optimization works by replacing AtomicFieldUpdater calls with calls to Unsafe, which eliminates the need for reflection checks. The R8 compiler can optimize these calls statically, resulting in a significant performance improvement. The optimization has been tested and verified through benchmarks, which show a 2x improvement in coroutine performance. Additionally, the ART team is working on implementing similar optimizations natively at the VM level, which will provide further performance improvements. The optimization is available by default when using AGP 9.2.0 or later, and it can also be used directly with R8 9.2.0. The performance improvement is significant, with some benchmarks showing a 2x improvement in coroutine performance. Overall, the optimization is an important step in improving the performance of Android apps that use coroutines and Kotlin. The optimization has been successfully tested and implemented, and it is now available for use in Android apps. The Android team continues to work on optimizing the performance of Android apps, and this optimization is an important part of those efforts.