Skip to content

Instantly share code, notes, and snippets.

@yigitozgumus
Created August 20, 2023 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yigitozgumus/11f93a209ebf6dd2f90fc32cefc2f373 to your computer and use it in GitHub Desktop.
Save yigitozgumus/11f93a209ebf6dd2f90fc32cefc2f373 to your computer and use it in GitHub Desktop.
Various Immutable List element update methods in Kotlin
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