Does any compressor take care of removing the switch cases which do not get called anywhere in the application?

function execute_case(id) {
    switch(id) {
    case 0:
       console.log("0");
       break;
    case 1:
       console.log("1");
       break;
    case 2:
       console.log("2");
       break;
    case 3:
       console.log("3");
       break;
    default:
       console.log("default");
       break;
    }
}

execute_case(1);

If the above is all I have, then theoretically cases 0,2,3 are dead code and will never be executed. Does any compressor have the intelligence of removing this code when minifying code?

I am taking a look at a piece of code which has over 200,000 cases in a switch statement, and hence the question.

Thanks, -Vikrant

有帮助吗?

解决方案

No Sir,

As id is a variable, no compressor will "know" that this can not happen. The compressors do not analyze variable values in switch statements and know how to remove them.

If you "know" these cases will not happen, just remove them yourself.

其他提示

Nothing is going to definitively give you a list of dead case statements. If it says it can there is either no possibility of another value (finite code branching) or it's lying. So unless you know every possible value that can be passed to execute_case, you'll be in the dark. (And I assume you don't given the question).

What you can do is place a small logger in that code that outputs/records the values being passed to that switch. Then, over [a good amount of] time and/or several thousand executions, track which ones are being hit and which ones aren't. I wouldn't necessarily remove ones not being hit, but maybe try deprecating them and wait for a longer duration/more executions until you reach the conclusion it's no longer necessary.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top