0

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?

Zoe
  • 27,060
  • 21
  • 118
  • 148
james
  • 131
  • 9
  • Check this post, here people have post there experiment's data https://stackoverflow.com/questions/67489671/is-coroutine-faster-than-thread-in-kotlin-and-why-how-can-i-get-the-time-of-c – ahjo4321hsotuhsa Sep 13 '22 at 16:16
  • Coroutines are not about performance, they are about concurrency and readability. – Sergio Sep 13 '22 at 18:21
  • This is not a valid comparison. You need a benchmarking library to do it properly. However, in this case, you should expect the coroutine to perform slightly worse. It’s not doing any parallelism and it has the extra overhead of setting up the coroutine. – Tenfour04 Sep 13 '22 at 19:29
  • Now compare coroutines to real threads... – Jorn Sep 14 '22 at 15:32
  • You're launching just one coroutine in which all the println's in the loop are done sequentially in the same thread. So what do you expect? – k314159 Sep 14 '22 at 16:11

0 Answers0