When we execute following functions after warmup, we get two different results.
good()
: 7msbad()
: 618ms
Why repeating outside the coroutineScope{...}
get a result that looks like invoking in serial?
suspend fun good() =
buildList {
coroutineScope {
// repeat inside the coroutineScope
repeat(100) {
add(async { delay(5) })
}
}
}.awaitAll()
suspend fun bad() =
buildList {
// repeat out of the coroutineScope
repeat(100) {
coroutineScope {
add(async { delay(5) })
}
}
}.awaitAll()
suspend fun main() {
// do some warm up
measureTimeMillis { good() }
.also { println("good: ${it}ms") }
measureTimeMillis { bad() }
.also { println("bad: ${it}ms") }
}
CodePudding user response:
As the documentation of the coroutineScope
function states:
This function returns as soon as the given block and all its children coroutines are completed.
Calling coroutineScope
suspends until all of its children coroutines are complete, so your bad()
example is running the jobs serially by design.