Search code examples
javascriptv8

Does V8 compiles only the code that we want to run?


I was learning the inner workings of V8 and got a bit confused with the way it translates our code, that is, say, we have an eventListener for button and when we click that button function will execute.

Is that true that:

  • only eventListener and function get interpreted into bytecode?
  • and only the code that we want to run is interpreted into bytecode?

Solution

  • (V8 developer here.) Generally yes. V8 compiles code (JavaScript to bytecode) on demand, so (usually) a JavaScript function will be compiled to bytecode the first time it is run.

    There may be exceptions to that statement: it's reasonable to assume that top-level code will be compiled immediately. When V8's parser sees (function, it also assumes that this is a so-called "IIFE", and compiles it eagerly based on the guess that it will end with })();. The specific details of such optimizations may change over time.

    You can safely assume that when you include a large library, then all that code will not be compiled up front, but only when it is executed.