gpt4 book ai didi

c# - 为什么这里没有发生尾调用优化?

转载 作者:可可西里 更新时间:2023-11-01 08:28:48 26 4
gpt4 key购买 nike

我们正在使用递归来查找因子并收到 StackOverflow 异常。我们读过 the C# compiler on x64 computers performs tail call optimizations :

JIT definitely does tailcals when running optimized code and not debugging.

在我们的程序中运行 dotnet --configuration release 可以做到这一点:

...                      
7214 is a factor of 1234567890
7606 is a factor of 1234567890
10821 is a factor of 1234567890
11409 is a factor of 1234567890

Process is terminated due to StackOverflowException.

为什么没有发生尾调用优化?

class Program
{
static void Main(string[] args)
{
const long firstCandidate = 1;
WriteAllFactors(1234567890, firstCandidate);
}

private static void WriteAllFactors(long number, long candidate)
{
if (number % candidate == 0)
{
System.Console.WriteLine($"{candidate} is a factor of {number}");
}

candidate = candidate + 1;
if(candidate > number / 2)
{
return;
}

WriteAllFactors(number, candidate);
}
}

最佳答案

VSadov 在他的回复中给出了明确的理由:

Generally JIT emits tail calls when it finds that profitable.

此外,他接着说:

This is a part that is not expressible in C#. Unlike inlining, which can be forced via attributes, tailcalling cannot be currently forced. If one needs to write the code like emitted by EmitMethodCall, he cannot use C#.

所以答案是虽然尾调用肯定可用和使用,但无法预测它们何时会被使用或强制它们在 C# 中使用。

关于c# - 为什么这里没有发生尾调用优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41404854/

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