-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Switch-case optimization #715
Comments
Bump. Also, I forgot to mention another required caveat: all cases with bodies must break or return at the end. The last case, or the default block if it exists, may omit it. If there is any branching at the end, all possible outcomes must end. Examples: // Good
switch (!1) {
case !cond: foo(); break;
}
switch (!1) {
case !cond: foo(); break;
case x !== y:
}
switch (!1) {
case !cond: foo(); break;
default:
}
switch (!1) {
case !cond: return foo();
}
switch (!1) {
case !cond:
if (a) foo();
break;
}
switch (!1) {
case !cond:
if (a) {
return foo();
} else {
break;
}
} // Bad
switch (!1) {
case !cond: foo();
case x !== y:
}
switch (!1) {
case !cond: foo(); break;
case x !== y:
}
switch (!1) {
case !cond: foo();
default:
}
switch (!1) {
case !cond:
if (a) foo();
case x !== y:
}
switch (!1) {
case !cond:
if (a) {
foo();
} else {
break;
}
case x !== y:
} |
Most common cases are covered by |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It would be nice if this could better optimize output like the following below:
Input:
Output:
This is rare in idiomatic JavaScript, but is frequently spit out of compilers. This could easily be made a lot smaller if it's converted into an if-else or ternary:
Better:
Best: (may already happen as a consequence)
Any
switch (false)
,switch (true)
,switch (!0)
, orswitch (!1)
could easily benefit from this transformation.Input:
Output:
Better:
Best:
As an added caveat for this to remain safe, uncoerced results still have to be checked with
===
, as per ES spec:Input:
Output:
Also, this should only be applied if the condition is
true
,false
,!0
, or!1
.The text was updated successfully, but these errors were encountered: