Kotlin - Difference between "forEachIndexed" and "for in" loop

Viewed 12306

I am confused on what are the advantages/disadvantages of each of these approaches (assuming I need to use both index and product):

products.forEachIndexed{ index, product ->
    ...
}

for ((index, product) in products.withIndex()) {
    ...
}

products here is a simple collection.

Is there any performance/best practice/etc argument to prefer one over the other?

1 Answers

No, they are the same. You can read the source of forEachIndexed and withIndex.

public inline fun <T> Iterable<T>.forEachIndexed(action: (index: Int, T) -> Unit): Unit {
    var index = 0
    for (item in this) action(index++, item)
}


public fun <T> Iterable<T>.withIndex(): Iterable<IndexedValue<T>> {
    return IndexingIterable { iterator() }
}

forEachIndexed use a local var to count the index while withIndex create a decorator for iterator which also use a var to count index. In theory, withIndex create one more layer of wrapping but the performance should be the same.

Related