File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed
Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change 1+ # Parallel coroutine operations on Kotlin collections
2+ Provides parallelized map, ~~ reduce~~ , ~~ etc.~~ operations using coroutines in Kotlin.
3+
4+ At this point, there is only a parallel map implementation called .mapParallel(). It is implemented like this.
5+ ``` kotlin
6+ suspend fun <T , R > Iterable<T>.mapParallel (transform : (T ) -> R ): List <R > = coroutineScope {
7+ map { async { transform(it) } }.map { it.await() }
8+ }
9+ ```
10+
11+ Example of using the parallel map operation.
12+ ``` kotlin
13+ fun showCase () {
14+ var list = listOf (1 ,2 ,3 )
15+ runBlocking(Dispatchers .Default ) {
16+ var mappedList = list.mapParallel { it * 2 } // Results in [2,4,6]
17+ }
18+ }
19+ ```
20+ If you want to achieve multithreading, make sure to run the coroutine with the Default dispatcher.
21+
22+ ## Future
23+ In the future, I would like parallel reduce and other transformation functions to be implemented,
24+ as well as chunked variations of the map and future operations.
25+ Chunked operations could potentially improve performance since they would split the collection into just a couple of segments,
26+ which would be processed each by a single thread. That could benefit from data locality and lesser thread management.
You can’t perform that action at this time.
0 commit comments