What features of Scala have low performance

Recently, I wandered around: how does Scala run on the JVM and the latter is optimized for certain types of operations, are there functions whose implementation is really inefficient on the JVM and which therefore should be discouraged? Could you also explain why they are ineffective?

The first candidate will be programming functionalities. As I know, functions are special classes with a method apply, which obviously creates additional overhead compared to languages ​​where functions are only blocks of code.

+5
source share
1 answer

- , .

Scala , .

:

(1 to 20).map(x => x*x).sum

val a = new Array[Int](20)
var i = 0
while (i < 20) { a(i) = i+1; i += 1 }  // (1 to 20)
i = 0
while (i < 20) { a(i) = a(i)*a(i); i += 1 }   // map(x => x*x)
var s = 0
i = 0
while (i < 20) { s += a(i); i += 1 }  // sum
s

. - 16 . ; - . , , , .

2 Int, Long Double.

. !

, , - , . :

def doOdd(a: Array[Char], f: (Char, Boolean) => Char) = {
  var i = 0
  while (i<a.length) { a(i) = f(a(i), (i&1)==1); i += 1 }
  a
}

val text = "The quick brown fox jumps over the lazy dog".toArray
val f = (c: Char, b: Boolean) => if (b) c.toUpper else c.toLower

scala> println( doOdd(text, f).mkString )
tHe qUiCk bRoWn fOx jUmPs oVeR ThE LaZy dOg

, ! ,

trait Func_CB_C { def apply(c: Char, b: Boolean): Char }
val g = new Func_CB_C {
  def apply(c: Char, b: Boolean) = if (b) c.toUpper else c.toLower
}
def doOdd2(a: Array[Char], f: Func_CB_C) = {
  var i = 0
  while (i<a.length) { a(i) = f(a(i), (i&1)==1); i += 1 }
  a
}

? 3 . (Int, Int) => Int ( Int/Long/Double Unit/Boolean/Int/Long/Float/Double return), - .

, , , .

Scala . , , , - . . , ,

val v = (1 to 1000).to[Vector]
v.map(x => x*(x+1))

val u = (1 to 1000).to[Vector].par
u.map(x => x*(x+1))

, , ?

! 10 - ( , )

, , , , . , , , , , . , , . , !

+7

All Articles