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")
}