gpt4 book ai didi

php - PHP是否优化尾递归?

转载 作者:IT王子 更新时间:2023-10-29 01:12:18 26 4
gpt4 key购买 nike

我写了一小段代码,我相信如果尾递归被优化的话应该会成功,但是它炸毁了堆栈。我应该断定 PHP 没有优化尾递归吗?

function sumrand($n,$sum) {
if ($n== 0) {
return $sum;
}
else {
return (sumrand($n-1,$sum+rand(0,1)));
}
}
echo sumrand(500000,0)."\n";

最佳答案

这是为此生成的操作码(抱歉出现奇怪的表示):

Global
-------------------------------------------------------------------------------
BCDCAC 0003: NOP ()
BCDD24 0012: SEND_VAL (CONST: "500000")
BCDD9C 0012: SEND_VAL (CONST: NULL)
BCDE14 0012: DO_FCALL (CONST: "sumrand") -> VAR 0
BCDE8C 0012: CONCAT (VAR 0, CONST: "\n") -> TMP_VAR 1
BCDF04 0012: ECHO (TMP_VAR 1)
BCDF7C 0014: RETURN (CONST: "1")

Functions
-------------------------------------------------------------------------------
sumrand (17 op)
BCFABC 0003: RECV (CONST: "1") -> CV 0 ($n)
BCFB34 0003: RECV (CONST: "2") -> CV 1 ($sum)
BCFBAC 0004: IS_EQUAL (CV 0 ($n), CONST: NULL) -> TMP_VAR 0
BCFC24 0004: JMPZ (TMP_VAR 0, &(BCFD18+6))
BCFC9C 0005: RETURN (CV 1 ($sum))
BCFD14 0006: JMP (&(BD01C8+10))
BCFD8C 0008: INIT_FCALL_BY_NAME (NULL, CONST: "sumrand")
BCFE04 0008: SUB (CV 0 ($n), CONST: "1") -> TMP_VAR 1
BCFE7C 0008: SEND_VAL (TMP_VAR 1)
BCFEF4 0008: SEND_VAL (CONST: NULL)
BCFF6C 0008: SEND_VAL (CONST: "1")
BCFFE4 0008: DO_FCALL (CONST: "rand") -> VAR 2
BD005C 0008: ADD (CV 1 ($sum), VAR 2) -> TMP_VAR 3
BD00D4 0008: SEND_VAL (TMP_VAR 3)
BD014C 0008: DO_FCALL_BY_NAME () -> VAR 4
BD01C4 0008: RETURN (VAR 4)
BD023C 0010: RETURN (CONST: NULL)

所以,不,看起来肯定不是这样。

关于php - PHP是否优化尾递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6171807/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com