okarm
11/18/2021, 12:00 AMList.fastForEach
https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/runtime/runtime/src/commonMain/kotlin/androidx/compose/runtime/snapshots/ListUtils.kt;l=27
/**
* Iterates through a [List] using the index and calls [action] for each item.
* This does not allocate an iterator like [Iterable.forEach].
*/
@OptIn(ExperimentalContracts::class)
internal inline fun <T> List<T>.fastForEach(action: (T) -> Unit) {
contract { callsInPlace(action) }
for (index in indices) {
val item = get(index)
action(item)
}
}
Is this something that the standard library might be interested in? Yes/no and why?jw
11/18/2021, 12:07 AMjw
11/18/2021, 12:08 AMjw
11/18/2021, 12:08 AMjw
11/18/2021, 12:08 AMephemient
11/18/2021, 1:09 AMmcpiroman
11/18/2021, 10:45 AMGeorge Mount
11/18/2021, 6:39 PMfastForEach
it was named something like forEachByIndex
, but that quickly gets confusing when you have forEachIndexedByIndex
.George Mount
11/18/2021, 6:44 PMRandomAccess
which can be quite expensive, and I didn't want my inline
function to be bloated with two implementations.
The "fast" prefix was the best we could come up with at the time. Naming is hard.
We don't expect application developers to need the performance gains from iterating over lists with indices.
I had a similar experience with ArrayList
and found that it is slower than having my own implementation, so we also have MutableVector
, which is essentially similar, but with no interfaces. I believe the main performance gain from that is the lack of "invoke virtual" because everything is final.George Mount
11/18/2021, 6:51 PMRandomAccess
and then choosing to implement with an index or iterator would be worth while in a general case.
I don't know enough about differences between ART and JavaVM and native implementations to know if there is a common implementation that is best for all of them or if it would have to be different to get the best performance.
This takes work and maintenance.ephemient
11/19/2021, 5:57 AMephemient
11/19/2021, 6:01 AM/**
* Even more so than usual, do not modify the underlying list while it is being accessed.
*/
fun <T> List<T>.unsafeForEach(...)