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
The quickest way to find dead code is to use a good IDE. Delete unused code and unneeded files. In the case of an unnecessary class, Inline Class or Collapse Hierarchy can be applied if a subclass or superclass is used. To remove unneeded parameters, use Remove Parameter.
The break KeywordIt is not necessary to break the last case in a switch block. The block breaks (ends) there anyway. Note: If you omit the break statement, the next case will be executed even if the evaluation does not match the case.
Use the break Keyword to Come Out of a Switch Case In JavaScript, the break keyword is used to stop the execution of the switch case and comes out of it. We can apply the break keyword after every case of the switch case if we want to execute only a single case from the switch case.
The switch case statement in JavaScript is also used for decision-making purposes. In some cases, using the switch case statement is seen to be more convenient than if-else statements. Consider a situation when we want to test a variable for hundred different values and based on the test we want to execute some task.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With