console.log 避免最大调用堆栈
console.log avoid maximum call stack
下面的代码按预期出现错误 Maximum call stack size exceeded
。
function recurrent (i = 0) {
recurrent(++i)
}
recurrent ()
我预计这也超过了最大调用堆栈。
但是,它运行了,为什么?
function recurrent (i = 0) {
console.log(i)
recurrent(++i)
}
recurrent ()
结果:
打印到一个数字并停止,但没有错误。
...
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
我在 Windows10
上使用 NodeJs 10
更新
Chrome 出错
正如人们所预料的那样,它们都会以完全相同的方式失败。只是日志语句将函数减慢到它可能不会立即失败的程度。
这是使用 time
对每个版本计时的结果:
# With logging:
...
RangeError: Maximum call stack size exceeded
real 0m0.204s
user 0m0.171s
sys 0m0.035s
# Without logging
...
RangeError: Maximum call stack size exceeded
real 0m0.082s
user 0m0.054s
sys 0m0.021s
在 Chrome 中进行测试时会发生相同的过程,但是要慢得多。在抛出 RangeError
之前花了 30 多秒。
下面的代码按预期出现错误 Maximum call stack size exceeded
。
function recurrent (i = 0) {
recurrent(++i)
}
recurrent ()
我预计这也超过了最大调用堆栈。 但是,它运行了,为什么?
function recurrent (i = 0) {
console.log(i)
recurrent(++i)
}
recurrent ()
结果:
打印到一个数字并停止,但没有错误。
...
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
我在 Windows10
上使用 NodeJs 10更新
Chrome 出错
正如人们所预料的那样,它们都会以完全相同的方式失败。只是日志语句将函数减慢到它可能不会立即失败的程度。
这是使用 time
对每个版本计时的结果:
# With logging:
...
RangeError: Maximum call stack size exceeded
real 0m0.204s
user 0m0.171s
sys 0m0.035s
# Without logging
...
RangeError: Maximum call stack size exceeded
real 0m0.082s
user 0m0.054s
sys 0m0.021s
在 Chrome 中进行测试时会发生相同的过程,但是要慢得多。在抛出 RangeError
之前花了 30 多秒。