Absolutely avoid calling forEach on Ranges. The co...
# announcements
a
Absolutely avoid calling forEach on Ranges. The cost is extremely high at around 300% https://sites.google.com/a/athaydes.com/renato-athaydes/posts/kotlinshiddencosts-benchmarks
1
👎 1
🧌 1
b
I am skeptical...
k
For each is inline though, right? If so, the foreach and the lambda aren't present in the generated bytecode, and there's no performance hit.
b
I no longer believe any findings in this article
1
k
@benleggiero Really strange that nobody seems to mention this in the reddit comments about this post: https://www.reddit.com/r/programming/comments/6jegsg/kotlin_hidden_costs_benchmarks/ They did complain a lot about the earlier article without benchmarks.
d
The reason why forEach (and other high-order functions) are considerably slower on ranges is that they allocate an interator for range, and everything is dispatched virtually. HotSpot can optimize it, if the stars are right. Dalvik and ART can't. So basically you pay for an extra layer of abstraction. Ranges in
for
are handled as compiler intrinsics.
One more advice for performance-conscious: prefer
until
to
..
in for loops. In almost every single case it will have the same effect (unless your upper bound can be
Int.MAX_VALUE
, but usually you don't care). That way the generated code would be almost the same as if you had a Java loop such as
for (int i = a; i < b; ++i) { ... }
, and it looks like HotSpot and both Android RTs optimize such loops better.