Jared Rieger
02/21/2022, 11:53 AMmap function in kotlin. If I contrast this to Javas parallel stream, the java stream is far faster than the standard kotlin map function.
suspend fun <I, O> Iterable<I>.pMap(f: suspend (I) -> O): List<O> = coroutineScope {
map {
async { f(it) }
}.awaitAll()
}
val aP = (1..1000000).toList()
@OptIn(ExperimentalTime::class)
suspend fun main(args: Array<String>) {
val timeP = measureTime {
aP.parallelStream().map { it.plus(6) }
aP.parallelStream().filter { it == 800000 }
}
println(timeP)
val time = measureTime {
aP.map { it.plus(6) }
aP.filter { it == 800000 }
}
println(time)
}
What’s going on here? my expectation would have been that the pMap function to be on par with java’s parallelStream.Tijl
02/21/2022, 12:27 PMTijl
02/21/2022, 12:27 PMTijl
02/21/2022, 12:28 PM12.932808ms
1.844329msTijl
02/21/2022, 12:29 PMTijl
02/21/2022, 12:33 PMTijl
02/21/2022, 12:34 PM3.750947ms
1.015118225sJared Rieger
02/21/2022, 12:37 PM3.796603ms
1.271090msJared Rieger
02/21/2022, 12:39 PMTijl
02/21/2022, 12:39 PMsleep to see the differenceTijl
02/21/2022, 12:40 PMJared Rieger
02/21/2022, 12:41 PMJared Rieger
02/21/2022, 12:42 PMwithContext block is that it’s not as clean as just chaining parallelStream . Would there be a way to wrap the pMap function in a context?Jared Rieger
02/21/2022, 12:43 PMsuspend fun <I, O> Iterable<I>.pMap(f: suspend (I) -> O): List<O> =
withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
coroutineScope {
map {
async { f(it) }
}.awaitAll()
}
}bezrukov
02/21/2022, 1:03 PMcoroutineScope builder, withContext(io) is enough to wrap it into contextTijl
02/21/2022, 1:04 PMpMap but never use it. (and there is no pFilter)Tijl
02/21/2022, 1:17 PMTijl
02/21/2022, 1:24 PMJared Rieger
02/21/2022, 2:01 PMJared Rieger
02/21/2022, 2:02 PMsuspend fun <I, O> Iterable<I>.pcMap(f: suspend (I) -> O): List<O> =
withContext(<http://Dispatchers.IO|Dispatchers.IO>) { // has many threads
map {
async { f(it) }
}.awaitAll()
}bezrukov
02/21/2022, 4:23 PM