Scala模式匹配性能

Ble*_*ezz 6 performance scala pattern-matching

我从coursera"scala specialization"做作业时遇到了这个问题(这是简化版,不包含任何作业细节,只是数组遍历)

val chars: Array[Char] = some array

def fun1(idx:Int):Int = {
    some code here (including the stop condition)

    val c = chars(idx)
    c match{
      case '(' => fun1(idx+1)
      case  _  => fun1(idx+1)
    }

}
Run Code Online (Sandbox Code Playgroud)

这段代码慢了4倍

def fun2(idx: Int):Int = {
    some code here (including the stop condition)

    val c = chars(idx)
    (c == '(') match{
      case true => fun2(idx+1)
      case  _  => fun2(idx+1)
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在做的就是改变模式匹配(我使用ScalMeter运行它,所以我相信统计数据).

谁能解释这种行为?

Vic*_*roz 3

我只能确认第一个match慢了约 50%,而不是 4 倍(2.11.8)。无论如何,如果你查看字节码,你会发现第一个match被翻译为tableswitch指令,通常用于具有switch多种选择的 Java 语句,基本上是一个查找 goto,而第二个被翻译为if. 所以第二个match很简单:

if (c == '(') fun2(idx+1) else fun2(idx+1)
Run Code Online (Sandbox Code Playgroud)