From scala docs, I understand @switch annotation is to tell compiler to verify that the match expression has been compiled to a tableswitch or lookupswitch and issue an error if it instead compiles into a series of conditional expressions.
Now my question is, if compilation is successful, then does it make any difference to generated byte code, as compared to if @switch annotation is not used at all?
Consider below two sample code versions,
Version 1
import scala.annotation.switch
val x = 5
(x: @switch) match {
case 1 => println("1")
case 2 => println("2")
case _ => println("something else")
}
Version 2
val x = 5
(x) match {
case 1 => println("1")
case 2 => println("2")
case _ => println("something else")
}
Isn't that both versions will result in same byte code instructions on compilation?
Both versions result in identical bytecode. You can test this by pasting one version into the REPL, doing :javap -
to disassemble it, and then repeating for the other version.
@switch has better performance it your pattern matching is simple, because it uses mapping table instead of decision tree. As internal structure is table , so it can directly go the right "case". For more information -http://alvinalexander.com/scala/using-match-expression-like-switch-statement
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With