1

Below is the piece of code which I was trying out. there are two blocks of code. the first one creates a million threads/coroutines asynchronously in map and then later adds them up. the second block creates the million coroutines and adds them in the for loop and then prints in out. According to me the first one should be faster as it creates them in parallel . the second one should be slow as you are creating million in one coroutine.

if my question makes sense at all I would like to get some understanding of this.

fun main() {
    //first block
    val elapsed1 = measureTimeMillis {
        val deferred = (1..1000000).map { n->
            GlobalScope.async{
                n
            }

        }
        runBlocking {
            val sum  = deferred.sumByDouble { it.await().toDouble() }
            println(sum)
        }
    }

    //second block
    val elapsed2 = measureTimeMillis {
        val def2 = GlobalScope.async{
            var j = 0.0;
            for(i in 1..1000000) {
                j+=i
            }
            j
        }
        runBlocking {
            val s = def2.await()
            println(s)
        }
    }

    println("elapsed1 $elapsed1")
    println("elapsed2 $elapsed2")

}
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
sinsanarya
  • 73
  • 12
  • 1
    More threads does not mean *faster*. There is overhead when running threads, especially when you exceed the number of CPU cores, and a million threads means a lot of that overhead. The overhead is called *context switching*, and a Google search for that phrase should find more information for you. – Ken White Feb 25 '21 at 01:35
  • The first block creates 1000000 coroutines, the second block creates a single coroutine. For the rest you're just summing a bounch of numbers on the same thread which doesn't take long anyway. The first block is going to be much slower. – al3c Feb 25 '21 at 11:22

1 Answers1

0

Please note that, for above small block of code, it is very difficult determine which one is faster than another.
Also, the result of above execution may vary from system to system.
Hence, we cannot confirm which block of code is faster just by running above steps.

Also, I request you to please refer to the following article to get more clarity around this area:

What is microbenchmarking?

SVK
  • 676
  • 1
  • 5
  • 17