If you try 9n**9n**9n in Chrome's console, Chrome breaks (it resembles an infinite loop). Why does this happen?

前端 未结 3 1337
半阙折子戏
半阙折子戏 2021-02-14 04:16

If you try 9n**9n**9n in Chrome\'s console, Chrome breaks (it resembles an infinite loop).

  • Does the V8 engine lack the implementation for this case?
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-14 04:43

    The answer as to why 9**9**9 returns Infinity is because it doesn't take very long to overflow the maximum value (around 2^1024). It might even shortcut it with the ** as see if the first number >= 2 and the second number > 1024, then it will be Infinity.

    With BigInt, it can represent much, much larger numbers, so that's what it tries to do. It takes a long time to reach "Infinity" with BigInt (EDIT: which would actually be a RangeError exception). Finding 387420489 can be done pretty quick, but 9n**387420489n, where it is multiplying BigInts almost 400 Million times...that takes a while.

    A BigInt operation is much slower than a regular int operation. I expect you might get a result (or a RangeError exception) if you wait 20-30 minutes, but could be much longer.

提交回复
热议问题