lampepfl / dotty-feature-requests

Historical feature requests. Please create new feature requests at https://github.com/lampepfl/dotty/discussions/new?category=feature-requests
31 stars 2 forks source link

automatically optimise loops over Range #308

Closed strelec closed 2 years ago

strelec commented 2 years ago

Minimized code

val range = 1 to 100 by 5
for (i <- range if f(x)) return i

Expectation

For loops over a scala Range should desugar to a java for loop. This should be guaranteed by a spec, so programmers can rely on it.

Why?

  1. I think programmers should have access to Java primitive building blocks to optimize tight loops (after doing a profiling of the runtime). Right now, only a while() statement is available, which forces you to use a mutable var, and that is not ideal.

  2. JVM optimizer can do many optimizations on bare for loops (loop unswitching, loop peeling), that I think it cannot do on foreach with a lambda.

  3. As the code is generated currently, returning from within a loop causes non local return with a large penalty.

  4. Many places in the Scala collections library could be simplified (while loops could be rewritten to the new for loops).

Example of desugaring

for (int i = range.start; i <= range.end, i += range.step) {
   if (f(i)) return i
}
SethTisue commented 2 years ago

corresponding Scala 2 ticket is https://github.com/scala/bug/issues/1338

griggt commented 2 years ago

also https://github.com/lampepfl/dotty/issues/8880

SethTisue commented 2 years ago

ah, seems like a straight-up duplicate of that one

SethTisue commented 2 years ago

(I'm not previously familiar with this new GitHub feature where you can close a ticket for different reasons. neither "completed" or "not planned" seems like an appropriate closed status, here. I guess "not planned" is a bit closer to correct, since it's now the other ticket that might, or might not, end up being "planned")