문제

(This is a bit of an X-Y problem, but I decided to ask the question that interests me, rather than the one I strictly need at the moment.) I know the various modern JavaScript engines have dead code eliminators and other means to get rid of code that has no effect or side effect, but how do you identify and/or compose such code?

The Wikipedia article on Dead code elimination gives one straightforward example of unreachable code, that is, code that happens after the unconditional return statement in a function. But can I count on the modern, major JavaScript engines to eliminate such code? For example, will Rhino or V8 eliminate this code?

function (foo) {
    return;
    return foo;
}

function (foo) {
    foo = foo;
}

and what about no op functions?

(function () {}(foo));
jQuery.noop(foo);

All of these examples fool JSHint, and while JSLint catches the weird assignment foo = foo, you can still trick it quite easily with the noops or a pair of variables:

function (foo) {
    var bar = foo;
}

If they can trick the static code analyzers, will they trick the engines themselves?

Short of closely examining the source of all the different JavaScript engines, is there any way to identify and/or construct the kind of code that will surely be eliminated before the program is ever run, and should it be considered a bug if such code is not elided, or is it merely a design choice?

도움이 되었습니까?

해결책

Finding dead code in JavaScript is a different beast than finding dead code in other languages like C++. For example, You can compile C++ to detect unreachable code, but obviously that's not possible with JavaScript.

The example of dead code you've given function () { return; var foo = 1; } is far less likely to occur than an event handler assigned to an HTML element that no longer exists on the page. No automated dead code analyzer could detect the latter.

What you can do is use a code coverage tool during your test runs and look for unused lines. You just have to ensure your test scripts are very thorough.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top