-
-
Save chrisbanes/ac842abd90b5810a1fe1ee05c7f0ac30 to your computer and use it in GitHub Desktop.
Sequence vs List benchmark
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.flow.asFlow | |
import kotlinx.coroutines.flow.filter | |
import kotlinx.coroutines.flow.map | |
import kotlinx.coroutines.flow.toList | |
import kotlinx.coroutines.runBlocking | |
import org.openjdk.jmh.annotations.Benchmark | |
import org.openjdk.jmh.annotations.Fork | |
import org.openjdk.jmh.annotations.Measurement | |
import org.openjdk.jmh.annotations.Scope | |
import org.openjdk.jmh.annotations.State | |
import org.openjdk.jmh.annotations.Warmup | |
import java.util.concurrent.TimeUnit | |
@State(Scope.Benchmark) | |
@Fork(1) | |
@Warmup(iterations = 2) | |
@Measurement(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS) | |
class SequenceBenchmark { | |
@Benchmark | |
fun list() { | |
DataRepository.getItemsList() | |
} | |
@Benchmark | |
fun sequence() { | |
DataRepository.getItemsListUsingSequence() | |
} | |
@Benchmark | |
fun flow() { | |
DataRepository.getItemsListUsingFlow() | |
} | |
} | |
private const val ITEM_SIZE = 100 | |
object Db { | |
fun getItems(): List<DbModel> { | |
return (0 until ITEM_SIZE).map { index -> | |
DbModel( | |
id = index, | |
rank = ITEM_SIZE - index, // reverse | |
isEnabled = index.mod(2) == 0, | |
) | |
} | |
} | |
} | |
object DataRepository { | |
fun getItemsList(): List<UiModel> { | |
return Db.getItems() | |
.filter { it.isEnabled } | |
.map { UiModel(it.id) } | |
} | |
fun getItemsListUsingSequence(): List<UiModel> { | |
return Db.getItems() | |
.asSequence() | |
.filter { it.isEnabled } | |
.map { UiModel(it.id) } | |
.toList() | |
} | |
fun getItemsListUsingFlow(): List<UiModel> = runBlocking { | |
Db.getItems() | |
.asFlow() | |
.filter { it.isEnabled } | |
.map { UiModel(it.id) } | |
.toList() | |
} | |
} | |
data class DbModel(val id: Int, val rank: Int, val isEnabled: Boolean) | |
data class UiModel(val id: Int) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment