Is it correct to assume that V8 will completely eliminate the dead code, structured like the following?
File module1.js
export const DEBUG = false
File module2.js
import { DEBUG } from './module1.js'
if (DEBUG) {
// dead code eliminated?
}
Please no comments like "the overhead of 'if' check is very small and you should XXX instead of asking this question". I just want to know if V8 is capable of this (yes/no, preferably with a little details of course).
V8 developer here. The answer is, as so often, "it depends".
V8's optimizing compiler supports dead code elimination, so yes, under the right circumstances, a conditional branch that can never be taken will get eliminated.
That said, in the specific example you posted, the top-level code won't get optimized (probably -- depends on what else is in there), so in that case no, the
if (DEBUG)
check will be compiled (to unoptimized bytecode) and executed -- once, because executing it once is way faster than first trying to optimize (and possibly eliminate) it.Another thing to consider is that V8 compiles functions "lazily", i.e. on demand. That means if you have an entire function that never gets called (e.g. because its only call site is in an
if (DEBUG)
-block andDEBUG
isfalse
), then that function won't even get compiled to bytecode, much less optimized code. That isn't dead code elimination in the traditional meaning of the term, but one could say that it's even better :-)In conclusion: if you have a little
DEBUG
-code sprinkled over your app, it's totally fine to leave it in. Either it'll be in rarely executed paths, in which case the cost of executing the checks doesn't matter; or it'll be in hot paths, in which case V8 will optimize it and eliminate the conditionals. However, if you have lots of such code, then removing it would have two advantages: download size, and parsing time. When JavaScript code arrives in the browser, the engine has no choice but to look at every single byte of it at least briefly (if only to figure out which functions there are, and which parts of the code are in the top-level and must be executed immediately), and the fewer bytes there are, the more quickly that step completes. Parsing is fast, but parsing half as much is even faster!