Pick the fix
This sorts a 2-million-item list. Which dispatcher should the function use?
suspend fun sortedScores(scores: List<Int>): List<Int> =
withContext(/* which dispatcher? */ Dispatchers.Default) {
scores.sortedDescending()
}Hint 1 of 1
Is this waiting, or computing?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A Dispatchers.Default
Correct. Sorting is pure CPU work, which belongs on the pool sized to the cores.
Why not the others?
- B
Dispatchers.IO. IO is for blocking waits. It works, but it is the wrong pool for CPU work. - C
Dispatchers.Main. That freezes the UI for the whole sort. - D
Dispatchers.Unconfined. It would keep running on the caller's thread, which may be main.