Search code examples
javascriptoptimizationv8

The JavaScript engine optimizes hot loops, but what about while(true)?


According to the YDKJSY book, if we use while(true), we will get an infinity loop until the browser crashes. In contrast, when I read about the JavaScript engine that optimizes hot loops or functions, I was confused. Here is an example from the https://mathiasbynens.be/notes/prototypes. In Javascript engine, a lot of things are done to optimize for-loops, and on the other hand, while(true){} does nothing until the browser crashes. What's the point?

Let’s take a look at a concrete example and see how the pipelines in the different engines deal with it. Here’s some code that gets repeated often, in a hot loop.

let result = 0;
for (let i = 0; i < 4242424242; ++i) {
    result += i;
}
console.log(result);

V8 starts running the bytecode in the Ignition interpreter. At some point the engine determines that the code is hot and starts up the TurboFan frontend, which is the part of TurboFan that deals with integrating profiling data and constructing a basic machine representation of the code. This is then sent to the TurboFan optimizer on a different thread for further improvements.

Here are some codes to consider:

while(true){}
console.log("Hi there!");

while(true){
console.log("Hi there!");
}

Solution

  • It doesn't matter what kind of loop you're using. Consider:

    let i = 0;
    while (true) {
      if (i > 4242424242) break;
      i++;
    }
    

    While that's technically a while (true)-loop, it doesn't run forever, and could well contain useful code. V8 doesn't care whether you write your loop like this, or in classic for loop syntax.

    Also, while (true) {} is not the only way to write a useless empty infinite loop, you can also do that using e.g. for (let i = 0; i >= 0; i++) {} or just for (;;);.

    In short:

    • JavaScript engines optimize hot code.
    • Long running loops count as "hot".
    • Whether it's a for or a while loop doesn't matter.
    • Whether it runs long or infinitely long doesn't matter. (For non-trivial examples, this is impossible to predict up front, and for trivial examples such as an empty infinite loop it doesn't really matter what the engine does, so it might as well always do the same thing: execute the loop you give it, leaving it up to you to decide whether that's a useful loop to execute.)