Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala @switch annotation, does it make any difference to generated byte code?

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?

like image 375
Kapil Avatar asked Jun 01 '14 22:06

Kapil


2 Answers

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.

like image 104
wingedsubmariner Avatar answered Oct 13 '22 17:10

wingedsubmariner


@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

like image 44
Goutam Chowdhury Avatar answered Oct 13 '22 17:10

Goutam Chowdhury