I wrote a simple program:
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.launch
import kotlin.system.measureNanoTime
fun countWithoutCoroutine(target: Int) {
for (i in 0..target) {
println(i)
}
}
suspend fun countWithCoroutine(target: Int) =
coroutineScope {
launch {
for (i in 0..target) {
println(i)
}
}
}
fun main() {
val timeWithCoroutine = runBlocking {
measureNanoTime {
countWithCoroutine(50)
}
}
println("Time Taken with coroutines : $timeWithCoroutine")
val timeWithoutCoroutine = measureNanoTime {
countWithoutCoroutine(50)
}
println("Time take without coroutines: $timeWithoutCoroutine")
}
The console output always seems to say that the time taken without coroutines is faster. Why is this?