Hello. I have lately taken interest in decompiling the output of Scala compiler (Scala 3.10.0 in my case).
I have always thought that being explicit by specifying None case is better. Two examples to compare:
x match {
case Some(y) =>
case None =>
}
x match {
case Some(y) =>
case _ =>
}
But first one (the recommended one) produces significantly worse output (java decompiled):
Option<Integer> option = ...;
if (option instanceof Some) {
return ...;
}
if (None$.MODULE$.equals(option)) {
return ...;
}
throw new MatchError(option);
}
vs.
Option<Integer> option = ...;
if (option instanceof Some) {
return ...;
}
return ...;
The problem is that throw new MatchError(option) makes the option escape, which means JDK cannot scalar-allocate the Option (stack or registers).
Note that this example is just the simplest one with Option, there are way more complex exhaustive patterns. For example, I was pattern matching on (Option[A], Option[B]), and MatchError then makes the Tuple2 escape, and on top of that the Scala optimizer (-opt) was not able to elide the tuple into two vals like it usually can, see example:
(x, y) match {
case (Some(a), Some(b)) =>
case (Some(a), None) =>
case (None, Some(b)) =>
case (None, None) => // just saying case _ => here avoid tuple allocation by -opt, and does not throw MatchError
}
How do I balance what is better for the code quality and what is better for performance? Is this a bug?