georgeci
06/18/2024, 11:01 AMIO
and Default
, specifically in Android development.
Question: We have a "small" JSON parsing operation. Which CoroutineDispatcher should I run it on?
I definitely don't want to do this on the Main
one.
IO
- has a larger pool. And there is a temptation to use it. Are there any reasons hidden at first glance to choose one or the other?kevin.cianfarini
06/18/2024, 11:08 AMDefault
.
The IO pool has more threads available to it because it's expected that those threads will get blocked with IO. You can only run in parallel the number of threads your CPU has capacity for, so trying to run JSON parsing on more threads than that won't produce any performance benefits.yschimke
06/18/2024, 12:25 PMkevin.cianfarini
06/18/2024, 12:27 PMval jsonString = "{ ... }"
val json = Json { ... }
val value = json.decodeFromString<SomeValue>(jsonString)
uli
06/18/2024, 12:54 PMwithContext
without incurring a big penalty. Even when loading and parsing are tightly interleaved.
Implementation note
This dispatcher and its views share threads with the Default dispatcher, so using `withContext(Dispatchers.IO) { ... }` when already running on the Default dispatcher typically does not lead to an actual switching to another thread. In such scenarios, the underlying implementation attempts to keep the execution on the same thread on a best-effort basis.uli
06/18/2024, 1:00 PMsuspend fun main() {
withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
println("Thread used for <http://Dispatchers.IO|Dispatchers.IO> ${Thread.currentThread().id}")
withContext(Dispatchers.Default) {
println("Thread used for Dispatchers.Default ${Thread.currentThread().id}")
}
println("Thread used for <http://Dispatchers.IO|Dispatchers.IO> ${Thread.currentThread().id}")
}
}
georgeci
06/18/2024, 1:12 PMkevin.cianfarini
06/18/2024, 1:18 PM