https://kotlinlang.org logo
#announcements
Title
# announcements
a

amorenew

07/03/2017, 3:03 AM
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

benleggiero

07/03/2017, 5:43 AM
I am skeptical...
k

karelpeeters

07/03/2017, 6:20 AM
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

benleggiero

07/03/2017, 6:23 AM
I no longer believe any findings in this article
1
k

karelpeeters

07/03/2017, 6:30 AM
@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

dmitry.petrov

07/03/2017, 8:38 AM
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.
3 Views