Skip to content

Instantly share code, notes, and snippets.

@afradigm
Last active February 6, 2025 10:11
Show Gist options
  • Save afradigm/d78367ba28ce16835479c01a5b293ad0 to your computer and use it in GitHub Desktop.
Save afradigm/d78367ba28ce16835479c01a5b293ad0 to your computer and use it in GitHub Desktop.
comparison between using traditional Threads and Kotlin Coroutines

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")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment