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!");
}
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:
for
or a while
loop doesn't matter.