Why do threads show better performance than coroutines?

I wrote 3 simple programs to check coroutine performance over threads. Each program performs many simple simple calculations. All programs were launched separately from each other. Besides runtime, I measured CPU utilization through the Visual VMIDE plugin .

  1. The first program performs all the calculations using the 1000-threadedpool. This code snippet shows worse results ( 64326 ms) compared to others due to frequent context changes:

    val executor = Executors.newFixedThreadPool(1000)
    time = generateSequence {
      measureTimeMillis {
        val comps = mutableListOf<Future<Int>>()
        for (i in 1..1_000_000) {
          comps += executor.submit<Int> { computation2(); 15 }
        }
        comps.map { it.get() }.sum()
      }
    }.take(100).sum()
    println("Completed in $time ms")
    executor.shutdownNow()
    

first program

  1. , 1000-threaded n-threaded ( n ). (43939 ms) , .

    val executor2 = Executors.newFixedThreadPool(4)
      time = generateSequence {
      measureTimeMillis {
        val comps = mutableListOf<Future<Int>>()
        for (i in 1..1_000_000) {
          comps += executor2.submit<Int> { computation2(); 15 }
        }
        comps.map { it.get() }.sum()
      }
    }.take(100).sum()
    println("Completed in $time ms")
    executor2.shutdownNow()
    

second program

  1. 41784 ms ( 41784 ms 81101 ms). , (, ). :

    time = generateSequence {
      runBlocking {
        measureTimeMillis {
          val comps = mutableListOf<Deferred<Int>>()
          for (i in 1..1_000_000) {
            comps += async { computation2(); 15 }
          }
          comps.map { it.await() }.sum()
        }
      }
    }.take(100).sum()
    println("Completed in $time ms")
    

third program

, kotlin, , . ? ?

+9
3

, - . . coroutine, , , , .

: , , , . , .

1000 000 , , , KotlinConf 2017:

suspend fun postItem(item: Item) {
    val token = requestToken()
    val post = createPost(token, item)
    processPost(post)
}

requestToken(), createPost() processPost() .

: suspend fun , :

fun requestToken() {
   Thread.sleep(1000)
   return "token"
}

.

suspend fun requestToken() {
    delay(1000)
    return "token"
}

, 1,000,000 , , OutOfMemoryException: unable to create new native thread, .

, , , , . : 1000 , - , .

Hazelcast Jet , : - . , , , . , , , , , , . Hazelcast Jet Java API. . coroutine, Java.

: Jet.

+15

Coroutines , , RAM .

+5

, . , 1 000 000 , 1 000 000 . Coroutine , . , .

0

Source: https://habr.com/ru/post/1691769/


All Articles