tim
05/26/2020, 8:57 PMfun doWorkWithIO() {
val time = measureTime {
IO.fx {
val effects = mutableListOf<Kind<ForIO, Int>>()
for (i in 0..1_000_000) {
val thing = effect { i }
effects.add(thing)
}
effects.forEach { it.bind() }
}.unsafeRunSync()
}
println("Default IO took $time")
}
fun doWorkWithFork() {
val time = measureTime {
IO.fx {
val effects = mutableListOf<Fiber<ForIO, Int>>()
for (i in 0..1_000_000) {
val thing = effect { i }.fork().bind()
effects.add(thing)
}
effects.forEach { it.join() }
}.unsafeRunSync()
}
println("Fibers took $time")
}
doWorkWithIO
completes in about 1 second and doWorkWithFork
runs in about 3 seconds. Are fibers using coroutines under the hood or threads? If so, whats the difference between them and effect? I assume they're for different things otherwise the wouldn't exist 🤷♂️ Is my code completely wrong!?pakoito
05/27/2020, 12:16 AMfork
is a way of eagerly starting a computation in IO
, and as Bob said, churning 1M executions in a CoroutineContext does come with some overhead, even if they resolve immediatelypakoito
05/27/2020, 12:17 AMtim
05/27/2020, 7:43 AMIO thread.id ForkJoinPool-1-worker-23
IO thread.id ForkJoinPool-1-worker-19
IO thread.id ForkJoinPool-1-worker-5
IO thread.id ForkJoinPool-1-worker-27
IO thread.id ForkJoinPool-1-worker-9
IO thread.id ForkJoinPool-1-worker-13
Fibers took 143ms
IO thread.id kotlinx.coroutines.DefaultExecutor
IO thread.id kotlinx.coroutines.DefaultExecutor
IO thread.id kotlinx.coroutines.DefaultExecutor
IO thread.id kotlinx.coroutines.DefaultExecutor
IO thread.id kotlinx.coroutines.DefaultExecutor
IO thread.id kotlinx.coroutines.DefaultExecutor
Default IO took 304ms
Is it safe to say here then, that doWorkWithIO
is executing serially whereas doWorkWithFork
is concurrent?pakoito
05/27/2020, 10:20 AMpakoito
05/27/2020, 10:20 AMIO.parMap
is also concurrent