到2020年,Scala编译器在模式匹配的情况下生成效率更高的字节码。公认答案中的绩效评论在2020年具有误导性。
模式匹配生成的字节码给if-else带来了激烈的竞争,有时,模式匹配获胜会带来更好,更一致的结果。
可以根据情况和简单性使用模式匹配或if-else。但是模式匹配具有较差的性能,结论不再有效。
您可以尝试以下代码片段并查看结果:
def testMatch(password: String, enteredPassword: String) = {
val entering = System.nanoTime()
password == enteredPassword match {
case true => {
println(s"User is authenticated. Time taken to evaluate True in match : ${System.nanoTime() - entering}"
)
}
case false => {
println(s"Entered password is invalid. Time taken to evaluate false in match : ${System.nanoTime() - entering}"
)
}
}
}
testMatch("abc", "abc")
testMatch("abc", "def")
Pattern Match Results :
User is authenticated. Time taken to evaluate True in match : 1798
Entered password is invalid. Time taken to evaluate false in match : 3878
If else :
def testIf(password: String, enteredPassword: String) = {
val entering = System.nanoTime()
if (password == enteredPassword) {
println(
s"User is authenticated. Time taken to evaluate if : ${System.nanoTime() - entering}"
)
} else {
println(
s"Entered password is invalid.Time taken to evaluate else ${System.nanoTime() - entering}"
)
}
}
testIf("abc", "abc")
testIf("abc", "def")
If-else time results:
User is authenticated. Time taken to evaluate if : 65062652
Entered password is invalid.Time taken to evaluate else : 1809
PS:由于数字是纳米精度的,因此结果可能无法与精确数字精确匹配,但有关性能的论点仍然很好。