title: Kotlin: coroutineScope is slower than GlobalScope
body: <p>I'm learning coroutines, and I encounter the following surprising (for me) behavior. I want to have a parallel map. I consider 4 solutions:</p>
  
  <ol>
  <li>Just <code>map</code>, no parallelism</li>
  <li><code>pmap</code> from <a href="https://jivimberg.io/blog/2018/05/04/parallel-map-in-kotlin/" rel="noreferrer">here</a>.</li>
  <li>Modification of item 2: I removed <code>coroutineScope</code> and use <code>GlobalScope</code>.</li>
  <li>Java's <code>parallelStream</code>.</li>
  </ol>
  
  <p>The code:</p>
  
  <pre><code>import kotlinx.coroutines.*
  import kotlin.streams.toList
  import kotlin.system.measureNanoTime
  
  inline fun printTime(msg: String, f: () -&gt; Unit) =
      println("${msg.padEnd(15)} time: ${measureNanoTime(f) / 1e9}")
  
  suspend fun &lt;T, U&gt; List&lt;T&gt;.pmap(f: (T) -&gt; U) = coroutineScope {
      map { async { f(it) } }.map { it.await() }
  }
  
  suspend fun &lt;T, U&gt; List&lt;T&gt;.pmapGlob(f: (T) -&gt; U) =
      map { GlobalScope.async { f(it) } }.map { it.await() }
  
  
  fun eval(i: Int) = (0 .. i).sumBy { it * it }
  
  fun main() = runBlocking {
      val list = (0..200).map { it * it * it }
      printTime("No parallelism") { println(list.map(::eval).sum()) }
      printTime("CoroutineScope") { println(list.pmap(::eval).sum()) }
      printTime("GlobalScope") { println(list.pmapGlob(::eval).sum()) }
      printTime("ParallelStream") { println(list.parallelStream().map(::eval).toList().sum()) }
  }
  </code></pre>
  
  <p>Output (without sums):</p>
  
  <pre><code>No parallelism  time: 0.85726849
  CoroutineScope  time: 0.827426385
  GlobalScope     time: 0.145788785
  ParallelStream  time: 0.161423263
  </code></pre>
  
  <p>As you can see, with <code>coroutineScope</code> there is almost no gain, while with <code>GlobalScope</code> it works as fast as <code>parallelStream</code>. What is the reason? Can I have a solution which has all advantages of <code>coroutineScope</code> with the same speed gain?</p>