C-style for loops in Scala 3 :: Sep 20, 2021
With Scala 3, we can easily implement fast C-style loops.
The usage looks like this.
The generated byte-code viewed in the CFR decompiler looks perfect; a simple Java for loop.
Lets also define some ergonomic variants:
But why not use for-do or while? Consider an example: given a two dimensional array, return true if the array contains some integer x.
It’s easy enough with Scala’s
However if you decompile the output you’ll see a monster:
Numbers are being boxed, Early Return is implemented by throwing Exceptions, and because x is in an outer scope, the second foreach lambda is capturing, which generates an anonymous class.
The performance is good with
while; the byte code looks exactly like the source. But it’s hard to read.
And finally, using loop():
Nearly as ergonomic as for-do, and the byte code looks much cleaner:
I wonder if for-do could be updated to behave like the loop() overloads, falling back to foreach(..) when required. I’m sure it would make some codebases a lot faster.