Currently, I am experimenting a bit with kotlin coroutines and I asked myself a question: Is there any significant performance gain when using coroutines? Let's look at some (theoretical) examples:
Example one
val myUnsortedList = listOf(1, 2, 5, 6, 3, 10, 100)
fun doStuffWithSorted(list: List<Int>) { ... }
// Without coroutine
val sortedList = myUnsortedList.sorted()
doStuffWithSorted(sortedList)
coroutineScope {
launch {
val sortedList = myUnsortedList.sorted()
doStuffWithSorted(sortedList)
}
}
Example two
fun doSomeHeavyOperations() { // doing heavy Operations but non blocking }
fun main() { doSomeHeavyOperations() }
//////////////// VERSUS //////////////////////
suspend fun doSomeHeavyOperations() { // doing heavy Operations but non blocking }
suspend fun main() {
coroutineScope {
launch {
doSomeHeavyOperations()
}
}
}
There are many more examples and maybe one of you could give some, where using coroutines is recommended. So my final question is (including the question above): When should it be considered to optimize the code performance with coroutines, and when is the expense bigger than the gained performance?