Removing dead code from switch enclosures in JavaScript

Does any compressor eliminate the removal of switch enclosures that are not 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 that I have, then theoretically cases 0,2,3 are dead code and will never be executed. Does any compressor have the intelligence of deleting this code when chopping code?

I am considering a piece of code that contains more than 200,000 cases in a switch statement, and therefore the question.

Thanks, -Vikrant

+8
performance javascript google-closure-compiler yui-compressor
source share
2 answers

No sir

Since id is a variable, the compressor will not β€œknow” that this cannot happen. Compressors do not analyze the values ​​of variables in switch statements and do not know how to remove them.

If you β€œknow,” these cases will not work, just delete them yourself.

+3
source share

Nothing is going to finally give you a list of allegations of a dead case. If he says that it may be either there is no possibility of another value (branching of the final code), or it lies. Therefore, if you do not know all the possible values ​​that can be passed to execute_case , you will be in the dark. (And I suppose you did not ask a question).

What you can do is place a small logger in this code that outputs / writes the values ​​passed to this switch. Then, over a [large amount] of time and / or several thousand performances, keep track of which ones fall and which do not. I would not necessarily delete those that did not fall, but perhaps try to condemn them and wait for a longer duration / more performances until you reach what you no longer need.

+3
source share

All Articles