Which iteration construct is better to use in Scala?

Recently, I started coding many of my Scala programming competitions. (Here you can take a look at the platform - http://codeforces.com/ )

Regarding the nature of the problems, I often have to iterate over an array or over input. For instance. There is an expression about the problem, which said that on the first line of input I will get the number M, and then I need to read M lines or integers or whatever. I am trying to use a different approach for this:

for (i <- 0 until M)
---- 
(0 until M).foreach
----
var i = 0
while (i < M)
---

Or even tail recursion

@tailrec
  def recursion(i: Int): Unit = {
    if (i < M) {
      doSomething()
      recursion(i + 1)
    }
  }

, , Scala ? (, , , )

P.S. , , tailrec - , . : https://gist.github.com/MysterionRise/5daa63fdbd5d058528fe

+4
2

:

, - JVM, - , , JVM JIT, . Scala, , ScalaMeter . , Scala, .

, :

  • -, while, ( ).
  • for - foreach, .
  • foreach ( ) , while ( ): benchmark 15 1000 ( , , Scala JRE...). , , , , .

:

johanandren.

+3

:

  • /
  • ( )

, , (tailrec - while) , for/foreach.

: Scala, .map , - .

+3

All Articles