Hi! I have a dispute about CoroutineDispatcher spe...
# coroutines
g
Hi! I have a dispute about CoroutineDispatcher specifically about the scenarios for using
IO
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?
k
JSON parsing is computational work that doesn't block on IO operations. You want
Default
. 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.
👍 2
y
If the JSON parsing indirectly involves reading from IO, network or a disk, then it could be relevant. It can be hard to separate the parts without fully fetching the bytes into memory.
👍 1
k
Yes, true, I had assumed what @georgeci meant by "small JSON parsing operation" was:
Copy code
val jsonString = "{ ... }"
val json = Json { ... }
val value = json.decodeFromString<SomeValue>(jsonString)
👍 1
u
And thats why dispatching from Default to IO and back is mostly optimized away. So you can dispatch loading of the data to IO and parsing to Default using
withContext
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.
☝️ 1
today i learned 1
You can check for yourself:
Copy code
suspend 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}")
    }
}
g
Thanks for answers. But my dispute was specifically about non IO operations. I'm just collecting arguments and opinions.
👍 1
k
If you aren’t doing IO then don’t use the IO dispatcher. It’s really that simple.
👍 5