Why does the value of typeof null change inside a loop?

前端 未结 4 1007
一向
一向 2020-11-29 20:50

Executing this snippet in the Chrome console:

4条回答
  •  自闭症患者
    2020-11-29 21:14

    It's actually a V8 JavaScript engine (Wiki) bug.

    This engine is used in Chromium, Maxthron, Android OS, Node.js etc.

    Relatively simple bug description you can find in this Reddit topic:

    Modern JavaScript engines compile JS code into optimized machine code when it is executed (Just In Time compilation) to make it run faster. However, the optimization step has some initial performance cost in exchange for a long term speedup, so the engine dynamically decides whether a method is worth it depending on how commonly it is used.

    In this case there appears to be a bug only in the optimized path, while the unoptimized path works fine. So at first the method works as intended, but if it's called in a loop often enough at some point the engine will decide to optimize it and replaces it with the buggy version.

    This bug seems to have been fixed in V8 itself (commit), aswell as in Chromium (bug report) and NodeJS (commit).

提交回复
热议问题