Array/List iteration without extra object allocations
As far as I know the only allocation-less way to define a for
loop is
for (i in 0..count - 1)
All other forms lead to either a Range
allocation or an Iterator
allocation. Unfortunately, you cannot even define an effective reverse for
loop.
To iterate an array without allocating extra objects you can use one of the following ways.
for
-loop
for (e in arr) {
println(e)
}
forEach
extension
arr.forEach {
println(it)
}
forEachIndexed
extension, if you need to know index of each element
arr.forEachIndexed { index, e ->
println("$e at $index")
}
Here is an example of preparing a list and iterate with index and value.
val list = arrayListOf("1", "11", "111")
for ((index, value) in list.withIndex()) {
println("$index: $value")
}
Output:
0:1
1:11
2:111
Also, following code works similar,
val simplearray = arrayOf(1, 2, 3, 4, 5)
for ((index, value) in simplearray.withIndex()) {
println("$index: $value")
}