string reverse(string str) pure nothrow
{
string reverse_impl(string temp, string str) pure nothrow
{
if (str.length == 0)
{
return temp;
}
else
{
return reverse_impl(str[0] ~ temp, str[1..$]);
}
}
return reverse_impl("", str);
}
据我所知,这段代码应该进行尾调用优化,但我不知道DMD是否正在这样做。哪个D编译器支持尾调用优化,他们会在这个函数上执行吗?
答案 0 :(得分:8)
通过查看反汇编,DMD对您的代码执行TCO:
_D4test7reverseFNaNbAyaZAya12reverse_implMFNaNbAyaAyaZAya comdat
assume CS:_D4test7reverseFNaNbAyaZAya12reverse_implMFNaNbAyaAyaZAya
L0: sub ESP,0Ch
push EBX
push ESI
cmp dword ptr 018h[ESP],0
jne L1C
LC: mov EDX,024h[ESP]
mov EAX,020h[ESP]
pop ESI
pop EBX
add ESP,0Ch
ret 010h
L1C: push dword ptr 024h[ESP]
mov EAX,1
mov EDX,offset FLAT:_D12TypeInfo_Aya6__initZ
push dword ptr 024h[ESP]
mov ECX,024h[ESP]
push ECX
push EAX
push EDX
call near ptr __d_arraycatT
mov EBX,02Ch[ESP]
mov ESI,030h[ESP]
mov 034h[ESP],EAX
dec EBX
lea ECX,1[ESI]
mov 01Ch[ESP],EBX
mov 020h[ESP],ECX
mov 02Ch[ESP],EBX
mov 030h[ESP],ECX
mov 038h[ESP],EDX
add ESP,014h
cmp dword ptr 8[ESP],0
jne L1C
jmp short LC
_D4test7reverseFNaNbAyaZAya12reverse_implMFNaNbAyaAyaZAya ends
end
答案 1 :(得分:4)
快速查看gdc生成的代码的一个非常好的资源是http://d.godbolt.org/。我们目前没有dmd等价物。