google / google/closure-compiler

Missed optimization opportunity: default label in switch-case makes other cases redundant

Open
#3,513 2 comments 0 reactions 0 assignees View on GitHub
internal-issue-created triage-done
Dominant language
JavaScript
Stars
7.7k
Forks
1.2k
Avg merge
2d 12h
Merged PRs (30d)
6

Description

Consider

```js
// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// ==/ClosureCompiler==

function foo(v) {
switch(v) {
case 1: case 2: return 100;
case 3: case 4: return 200;
default: return 100;
}
}

alert(foo(performance.now()));
```

Check [online](https://closure-compiler.appspot.com/home#code%3D%252F%252F%2520%253D%253DClosureCompiler%253D%253D%250A%252F%252F%2520%2540compilation_level%2520ADVANCED_OPTIMIZATIONS%250A%252F%252F%2520%2540output_file_name%2520default.js%250A%252F%252F%2520%253D%253D%252FClosureCompiler%253D%253D%250A%250Afunction%2520foo(v)%2520%257B%250A%2520%2520switch(v)%2520%257B%250A%2520%2520%2520%2520case%25201%253A%2520case%25202%253A%2520return%2520100%253B%250A%2520%2520%2520%2520case%25203%253A%2520case%25204%253A%2520return%2520200%253B%250A%2520%2520%2520%2520default%253A%2520return%2520100%253B%250A%2520%2520%257D%250A%257D%250A%2520%2520%250Aalert(foo(performance.now()))%253B).

This generates

```js
var a;
a: switch (performance.now()) {
case 1:
case 2:
a = 100;
break a;
case 3:
case 4:
a = 200;
break a;
default:
a = 100
}
alert(a);
```

but the `default:` section in the switch-case would turn the `case 1: case 2:` block redundant, and an equivalent code would be

```js
var a;
a: switch (performance.now()) {
case 3:
case 4:
a = 200;
break a;
default:
a = 100
}
alert(a);
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.