I'm new to Scala. When I am learning it by reading Scala code written by others, one of the most distinguishing feature I find in Scala code that is different from other languages is its pattern matching.
At the same time I feel the convenience and expressiveness it brings, I can't help being curious of the potential performance cost behind it -- generally speaking, how fast is match
?
Firstly, without "advanced" features such as matching parameters of constructors, match
in Scala, IMO, is the counterpart of switch-case
in other languages. For instance,
color match {
0 => println "color is red!"
1 => println "color is green!"
2 => println "color is blue!"
}
As a novice, I want to know if the code above is exactly as fast as equivalent code in if-else
statement?
Secondly, now taking those "advanced" features back, for instance:
expr match {
Animal(name) => ...
Animal(name, age) => ...
Animal(_, _, id) => ...
}
As for the code above or other features of match(list matching, pair matching, etc.), I am curious about how Scala implemented these fancy usage? And most importantly, how fast can I expect these code to be? (Say, are they still as fast as the match
in the first case? Or maybe slightly slower? Or extremely slow owing to the use of some technology such as reflection?)
Thanks in advance!