Switch translation
Guy Steele
guy.steele at oracle.com
Fri Apr 6 18:38:25 UTC 2018
> On Apr 6, 2018, at 1:58 PM, Brian Goetz <brian.goetz at oracle.com> wrote:
>
>
>>>
>>> int index=-1;
>>> switch (s.hashCode()) {
>>> case 12345: if (!s.equals("Hello")) break; index = 1; break;
>>> case 6789: if (!s.equals("World")) break; index = 0; break;
>>> default: index = -1;
>>> }
>>> switch (index) {
>>> case 0: ...
>>> case 1: ...
>>> default: ...
>>> }
>>>
>>> If there are hash collisions between the strings, the first switch must try all possible matching strings.
>>
>> I see why you use this structure, because it fits a general paradigm of first mapping to an integer.
>
> Or, "used", since this is the historical strategy which we're tossing over for the indy-based one.
Sorry, I incorrectly interpreted some of the transitional text.
>
>> I now suggest that a post-optimization might then turn this into:
>>
>> SUCCESS: {
>> DEFAULT: {
>> switch (s.hashCode()) {
>> case 12345: if (s.equals("Hello")) { stmts1; break SUCCESS; } else if (s.equals(“Goodbye")) { stmts3; break SUCCESS; } else break DEFAULT;
>
> Yes; the thing that pushed us to this translation was fallthrough and other weird control flow; by lowering the string-switch to an int-switch, the control structure is preserved, so any complex control flow comes along "for free" by existing int-switch translation. Of course, it's not free; we pay with a pre-switch. (When we added strings in switch, it was part of "Project Coin", whose mandate was "small features", so it was preferable at the time to choose a simpler but less efficient desugaring.)
Oops, I forgot about preserving fallthrough. Yuck. “Never mind."
Well, the post-optimization can still be used in situations where no fallthrough occurs. Can decide later whether it is worth the trouble to avoid the integer encoding.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.openjdk.java.net/pipermail/amber-spec-experts/attachments/20180406/e4e1b0f9/attachment-0001.html>
More information about the amber-spec-experts
mailing list