In this example, I conducted a comparison between using traditional Threads and Kotlin Coroutines to perform the same task. The result was fascinating! Coroutine execution proved to be significantly faster and more lightweight compared to Threads.
With the same resources:
- Execution time using Threads: 69,279 ms
- Execution time using Coroutines: 2,454 ms
This demonstrates the efficiency of coroutines, particularly in scenarios that require concurrency, as they consume fewer system resources and execute more quickly than traditional threads.
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() {
//coroutineExample()
threadExample()
}
private fun coroutineExample() {
val startTime = System.currentTimeMillis()
runBlocking {
repeat(1_000_000) {
launch {
print(".")
}
}
}
val endTime = System.currentTimeMillis()
println("\nExecution time: ${endTime - startTime} ms")
}
private fun threadExample() {
val startTime = System.currentTimeMillis()
val threads = mutableListOf<Thread>()
repeat(1_000_000) {
val thread = Thread {
print(".")
}
threads.add(thread)
thread.start()
}
threads.forEach { it.join() } // Wait for all threads to finish
val endTime = System.currentTimeMillis()
println("\nExecution time: ${endTime - startTime} ms")
}