[scala] 패턴 매칭 (pattern matching) 성능 주의 사항
스칼라에서 패턴 매칭 코드를 사용시 주의해야 할 것이다.
먼저 간단한 패턴 매칭 코드를 테스트해보자.
object Main extends App {
def matchTest(x: Int): String = x match {
case 1 => "1"
case 2 => "2"
case _ => "3"
}
println(matchTest(3))
}
이 코드를 scala 바이트 코드로 생성하면, 간단한 java match로 변환한다. 이런 경우는 특별히 주의할 사항은 없다.
def matchTest(x: Int): String = {
case <synthetic> val x1: Int = x;
(x1: Int) match {
case 1 => "1"
case 2 => "2"
case _ => "3"
}
};
만약, String 객체라면 어떨까?
object Main extends App {
def matchTest(x: String): String = x match {
case "1" => "1"
case "2" => "2"
case _ => "3"
}
println(matchTest("3"))
}
순차적인 if 문과 메소드가 생성된다.
case5(){
if (x1.$isInstanceOf[Count]())
matchEnd4(true)
else
case6()
};
case6(){
matchEnd4(false)
};
matchEnd4(x: Boolean){
x
}
...
def matchTest(x: String): String = {
case <synthetic> val x1: String = x;
case6(){
if ("1".==(x1))
matchEnd5("1")
else
case7()
};
case7(){
if ("2".==(x1))
matchEnd5("2")
else
case8()
};
case8(){
matchEnd5("3")
};
matchEnd5(x: String){
x
}
};
따라서 성능에 민감한 코드가 들어 있다면, 최대한 case 문의 앞쪽에 배치시켜야 한다.
접근 빈도가 가장 높은 데, 패턴 매칭의 case 문 맨 끝에 있다면 선형 시간의 worst 시간에 걸려, 최악의 성능을 낼 수 있다.