Why is Scala for loops slower than logically identical while loops?

I like the power of Scala to understand and how they integrate with any monadic type with map and flatMap. However, I would also like to do simple whole cycles without a serious speed penalty. Why does Scala not have the following two logically identical loops with the same execution performance or even compilation into the same byte code?

// This is slow...
for (i <- 0 until n) println(s"for loop with $i")

// This runs much faster. It runs roughly at the same speed as Java code doing an identical while or for loop.
var i = 0;
while (i < n) {
  println(s"while loop with $i")
  i += 1
}
+4
source share
1 answer

The main (but not only) reason why they are different is boxing.

In code:

for (i <- 0 until n) println(s"for loop with $i")

You pass an anonymous function println(s"for loop with $i")to understanding for (i <- 0 until n). This is equivalent to:

(0 until n) foreach (i =>
  println(s"for loop with $i")
}

-, , i int, Integer. Java Fixnum, , , , Smalltalk ( , , !)

-optimize , .

scalaxy/loops, :)

+4

Source: https://habr.com/ru/post/1523841/


All Articles