PHP 是否优化尾递归?
我写了一小段代码,我相信如果尾递归被优化的话应该会成功,但是它炸毁了堆栈。我应该得出 PHP 没有优化尾递归的结论吗?
function sumrand($n,$sum) {
if ($n== 0) {
return $sum;
}
else {
return (sumrand($n-1,$sum+rand(0,1)));
}
}
echo sumrand(500000,0)."\n";
I wrote a small piece of code that I believe should have succeeded if tail recursion was optimized, however it blew up the stack. Should I conclude PHP does not optimize tail recursion?
function sumrand($n,$sum) {
if ($n== 0) {
return $sum;
}
else {
return (sumrand($n-1,$sum+rand(0,1)));
}
}
echo sumrand(500000,0)."\n";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下是为此生成的操作码(对于奇怪的表示感到抱歉):
所以,不,看起来肯定不是这样。
Here are the generated opcodes for that (sorry for the strange representation):
So, no, it certainly doesn't seem so.
似乎是一个安全的假设,但事实并非如此。
Seems like a safe assumption that it's not.
重要的是要知道 PHP 是一种用 C 编写的脚本语言,因此必然会出现这种限制。底层 C 语言也缺乏优化:
http://rosettacode.org/wiki/Find_limit_of_recursion
正如您所看到的,PHP 并不是唯一不能优雅地处理事情的语言。
我建议使用 Erlang 和 MyPeb PHP/Erlang 桥来真正解决此类问题。
It is important to know that PHP is a scripting language written in C so limitations of this sort are bound to appear. The lack of optimization shows in the underlying C language also:
http://rosettacode.org/wiki/Find_limit_of_recursion
As you can see PHP is not the only language that does not handle things gracefully.
I recommend using Erlang and the MyPeb PHP/Erlang bridge for a true solution to a problem like this.