Strings in Switch

Jorge Ortiz jorge.ortiz at gmail.com
Mon Dec 7 15:14:21 PST 2009


The equivalent in Scala of "Strings in Switch" is pattern matching on
strings. In Scala this is implemented as nested if-else statements. This is
probably necessary because Scala's pattern matching has some additional
features (like matching only if a conditional is met, or matching on
extractors) that probably wouldn't mesh will with optimizations like
hashCode. That said, in my 2.5 years using Scala I've never once heard
anyone complain about the performance of pattern matching on strings. It'd
be interesting to see some benchmarks, but I'd guess that the difference in
performance between the equality approach and the hashCode approach is
unnoticeable unless you're matching on either really, really long strings or
a very, very large number of strings. Neither of these scenarios is likely
to be true for switch statements.

--j

On Mon, Dec 7, 2009 at 2:43 PM, Paul Benedict <pbenedict at apache.org> wrote:

> I see that syntactic sugar assumes that the compiler and the runtime
> environment both use the same string hashing algorithm. As noted, the
> algorithm has never changed since at least JDK 1.2. Even if unlikely,
> I don't feel comfortable with this assumption - I do not have an
> alternative to propose either -- but I thought it was worth voicing.
>
> Regardless, I see this as a pure detail of one possible
> implementation. Another implementation may not choose to use hash
> codes at all. Am I correct, or am I wrong and the JLS change will
> mandate the use of hashCode for switching?
>
> Paul
>
>



More information about the coin-dev mailing list