[Kotlin] for-loop with no additional object allocation

In Kotlin, we can use functions such as forEach, forEachIndexed, and map to iterate items in collection.

It’s convenient to use, but it comes with cost; those functions create additional objects like Iterator.

For most cases, it wouldn’t be a serious problem to have some temporary objects. However, when overriding onDraw method of View class, it’s prohibitted to allocate a new object within the method.

Basic for-loops in Kotlin are as follows;

for (x in 0..9)
for (x in 0 until 10)
for (x in 0 until 10 step 2)

In short, the second one is the one we are looking for.

For the first and the third case, IntRange and IntProgression are created respectively.

The document says until operator also returns a Range object, but the decompiled code doesn’t have any;

int var0 = 0;

for(byte var1 = 10; var0 < var1; ++var0) {
}

There is no object allocation and it’s just a plain for-loop.

Tested on Kotlin 1.4

Leave a Comment

Your email address will not be published. Required fields are marked *