为什么 .NET/C# 不针对尾调用递归进行优化? [英] Why doesn't .NET/C# optimize for tail-call recursion?

查看:27
本文介绍了为什么 .NET/C# 不针对尾调用递归进行优化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了关于哪些语言优化了尾递归的这个问题.为什么 C# 不尽可能优化尾递归?

I found this question about which languages optimize tail recursion. Why C# doesn't optimize tail recursion, whenever possible?

对于具体案例,为什么不将此方法优化为循环 (Visual Studio 2008 32 位,如果这很重要)?:

For a concrete case, why isn't this method optimized into a loop (Visual Studio 2008 32-bit, if that matters)?:

private static void Foo(int i)
{
    if (i == 1000000)
        return;

    if (i % 100 == 0)
        Console.WriteLine(i);

    Foo(i+1);
}

推荐答案

JIT 编译是在不花费太多时间进行编译阶段(从而显着减慢短期应用程序的速度)与不进行足够的分析以确保通过标准的提前编译保持应用程序的长期竞争力.

JIT compilation is a tricky balancing act between not spending too much time doing the compilation phase (thus slowing down short lived applications considerably) vs. not doing enough analysis to keep the application competitive in the long term with a standard ahead-of-time compilation.

有趣的是,NGen 编译步骤的目标并不是在优化中更加积极.我怀疑这是因为他们根本不希望出现行为依赖于 JIT 还是 NGen 对机器代码负责的错误.

Interestingly the NGen compilation steps are not targeted to being more aggressive in their optimizations. I suspect this is because they simply don't want to have bugs where the behaviour is dependent on whether the JIT or NGen was responsible for the machine code.

CLR 本身确实支持尾调用优化,但是特定语言的编译器必须知道如何生成相关的opcode 并且 JIT 必须愿意尊重它.F#'s fsc 将生成相关的操作码(尽管对于简单的递归,它可能只是转换整个事情直接进入 while 循环).C# 的 csc 没有.

The CLR itself does support tail call optimization, but the language-specific compiler must know how to generate the relevant opcode and the JIT must be willing to respect it. F#'s fsc will generate the relevant opcodes (though for a simple recursion it may just convert the whole thing into a while loop directly). C#'s csc does not.

有关详细信息,请参阅这篇博文鉴于最近的 JIT 更改,现在已过时).请注意,4.0 的 CLR 更改 x86、x64 和 ia64 会尊重它.

See this blog post for some details (quite possibly now out of date given recent JIT changes). Note that the CLR changes for 4.0 the x86, x64 and ia64 will respect it.

这篇关于为什么 .NET/C# 不针对尾调用递归进行优化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆