[英]javascript Factorial function got RangeError
const factorial = function(n, acc = 1){
if (n < 2) {
return acc;
}
return factorial(n - 1, n * acc);
};
const factorial_normal = function(n){
if (n < 2) {
return 1;
}
return n * factorial_normal(n - 1)
};
console.log(factorial(8956)); // RangeError: Maximum call stack size exceeded
console.log(factorial_normal(8960)); // Infinity
It's just a simple factorial function with javascript. 它只是一个简单的使用javascript的阶乘函数。 But I got a RangeError with the first function, which i do think it was a better solution cause i think it is faster and more stack-save.
但我得到了第一个函数的RangeError,我认为这是一个更好的解决方案,因为我认为它更快,更多的堆栈保存。 Is there something different in these two function that i've ever been known.
这两个功能有什么不同,我曾经知道。 Please help me, thanks.
请帮帮我,谢谢。
Because Node.js doesn't support tail call optimization, both of these functions will throw the RangeError: Maximum call stack size exceeded
error at some point. 因为Node.js不支持尾调用优化,所以这两个函数都会抛出
RangeError: Maximum call stack size exceeded
在某些时候RangeError: Maximum call stack size exceeded
错误。 When this will happen depends on two quantities: the maximum allowed size of the stack and the size of each individual stack frame. 何时发生这种情况取决于两个数量:堆栈的最大允许大小和每个堆栈帧的大小。 By default, the size of the stack is set to some constant value, which you can get by running the following command:
默认情况下,堆栈的大小设置为某个常量值,您可以通过运行以下命令获得该值:
node --v8-options | grep -e '--stack-size' -A 1
So, the only parameter left is the size of the stack frame. 因此,剩下的唯一参数是堆栈帧的大小。
factorial
stores two variables on the stack on each function call - acc
and n
. factorial
在每个函数调用的堆栈上存储两个变量 - acc
和n
。 Whereas factorial_normal
stores only one - n
. 而
factorial_normal
只存储一个 - n
。 It means that factorial
will run out of stack space sooner than factorial_normal
. 这意味着
factorial
将比factorial_normal
更快地耗尽堆栈空间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.