我从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) } }
这段代码慢了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) } }
我所做的只是改变模式匹配
(我使用ScalMeter运行它,所以我相信统计数据).
谁能解释这种行为?
解决方法
我只能确认第一场比赛慢了约50%,而不是4x(2.11.8).无论如何,如果你查看字节码,你会发现第一个匹配被转换为tableswitch指令,通常用于具有多个选择的Java switch语句,并且基本上是一个查找goto,而第二个被转换为if.所以第二场比赛很简单:
if (c == '(') fun2(idx+1) else fun2(idx+1)