Created
August 20, 2023 16:42
-
-
Save yigitozgumus/11f93a209ebf6dd2f90fc32cefc2f373 to your computer and use it in GitHub Desktop.
Various Immutable List element update methods in Kotlin
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 kotlin.random.Random | |
import kotlin.random.nextInt | |
import kotlin.time.measureTime | |
fun main() { | |
val dataset = ExperimentData(listSize = 100, updateTimes = 5000000) | |
val experiments = mutableListOf<Experiment>() | |
// region experments | |
Experiment( | |
name = "Map" | |
) { data -> | |
var componentList = data.componentList | |
data.updateList.forEach { index -> | |
componentList = componentList.map { | |
if (it.id == index) it.copy(payload = "Update") else it | |
} | |
} | |
}.also { experiments += it } | |
Experiment( | |
name = "Sublist" | |
) { data -> | |
var componentList = data.componentList | |
data.updateList.forEach { index -> | |
val targetComponent = componentList[index] | |
componentList = buildList<Container> { | |
addAll(componentList.subList(0,index)) | |
add(targetComponent.copy(payload = "Update")) | |
addAll(componentList.subList(index, componentList.lastIndex)) | |
} | |
} | |
}.also { experiments += it } | |
Experiment( | |
name = "MutableList" | |
) { data -> | |
var componentList = data.componentList | |
data.updateList.forEach { index -> | |
componentList = componentList.toMutableList().apply { | |
this[index] = this[index].copy(payload = "Update") | |
}.toList() | |
} | |
}.also { experiments += it } | |
Experiment( | |
name = "MutableList with extension" | |
) { data -> | |
var componentList = data.componentList | |
data.updateList.forEach { index -> | |
componentList = componentList.update(index) { it.copy(payload = "Update")} | |
} | |
}.also { experiments += it } | |
// endregion | |
experiments.forEach { it.runWith(dataset) } | |
} | |
data class ExperimentData( | |
private val listSize: Int, | |
private val updateTimes: Int | |
) { | |
val componentList = (0..listSize).map { Container(id = it) } | |
val updateList = buildList { | |
repeat(updateTimes) { add(Random.nextInt(0..listSize)) } | |
}.toList() | |
} | |
data class Experiment( | |
val name: String, | |
val experimentBlock: (ExperimentData) -> Unit | |
) { | |
fun runWith(data: ExperimentData) { | |
print("\nMethod: $name ") | |
val duration = measureTime { experimentBlock(data) } | |
print("| Duration: ${duration.absoluteValue}\n") | |
} | |
} | |
fun <T> List<T>.update(index: Int, block: (T) -> (T)): List<T> { | |
return this.toMutableList().apply { this[index] = block(this[index]) }.toList() | |
} | |
data class Container( | |
val id: Int, | |
val payload: String = "" | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment