I am testing the speed between Thread and Coroutine.
And I found out an interesting stuff.
When the number of Thread and Coroutine is very small, Thread is faster. However, when the number becomes bigger, Coroutine is much faster.
Here's the code that I tested out.
class ExampleUnitTest {
val reps = 1000000
val sumSize = 999
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
@Test
fun runInThread() {
var sum = 0
val threadList = ArrayList<Thread>()
println("[start] Active Thread = ${Thread.activeCount()}")
val time = measureTimeMillis {
repeat(reps) {
val mThread = Thread {
// println("start: ${Thread.currentThread().name}")
// Thread.sleep(1000L)
// println("end: ${Thread.currentThread().name}")
}
mThread.start()
threadList += mThread
}
println("[end] Active Thread= ${Thread.activeCount()}")
threadList.forEach {
it.join()
}
}
println("Time: $time ms\n")
}
@Test
fun runInCoroutine() {
var sum = 0
val jobList = ArrayList<Job>()
runBlocking {
println("[start] Active Thread = ${Thread.activeCount()}")
val time = measureTimeMillis {
repeat(reps) {
val job = launch(Dispatchers.Default) {
// println("start: ${Thread.currentThread().name}")
// delay(1000L)
// println("end: ${Thread.currentThread().name}")
}
jobList += job
}
println("[end] Active Thread= ${Thread.activeCount()}")
jobList.forEach {
it.join()
}
}
println("Time: $time ms\n")
}
}
}
try | reps size | Thread time(ms) | Coroutine time(ms) |
---|---|---|---|
1 | 10 | 1 | 63 |
2 | 100 | 8 | 65 |
3 | 1000 | 55 | 90 |
4 | 10000 | 426 | 175 |
5 | 100000 | 4089 | 395 |
6 | 1000000 | 43868 | 3165 |
At the end, it turns out Using coroutines is faster than using a lot of Threads.
However, I don't think only 'context switching' takes that much time since the task is empty and context switching work looks it's very tiny tiny. Does context switching can make that much big differences?