Scala模式匹配性能
发布时间:2020-12-16 18:49:22 所属栏目:安全 来源:网络整理
导读:我从coursera“ scala specialization”做作业时遇到了这个问题(这是简化版,不包含任何作业细节,只是数组遍历) val chars: Array[Char] = some arraydef fun1(idx:Int):Int = { some code here (including the stop condition) val c = chars(idx) c match{
我从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) } } 我所做的只是改变模式匹配 谁能解释这种行为? 解决方法
我只能确认第一场比赛慢了约50%,而不是4x(2.11.8).无论如何,如果你查看字节码,你会发现第一个匹配被转换为tableswitch指令,通常用于具有多个选择的Java switch语句,并且基本上是一个查找goto,而第二个被转换为if.所以第二场比赛很简单:
if (c == '(') fun2(idx+1) else fun2(idx+1) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |