带有尾递归优化的 C# 编译? [英] C# compilation with tail recursive optimization?

查看:22
本文介绍了带有尾递归优化的 C# 编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于stackoverflow的丰富财富,我一直在回答是否对c#代码进行尾递归优化.一些问题似乎在谈论

Based on the rich wealth of stackoverflow, I've been getting on and off answers on whether the tail recursive optimization is done to specifically c# code. A few of the questions appeared to talk about

  1. 对正在发布的较新版本 .net 中的优化的推测
  2. 将应用程序构建为 x64 位应用程序以实现优化
  3. 在 Visual Studio 中从调试版本切换到发布版本以实现优化
  4. 根本没有优化,微软社区声称他们不会对安全问题"进行尾递归优化(并没有真正理解这个问题)
  5. 随机发生

从 C# 4.0 (Visual Studio 2013/2015) 开始,如果完全可以确保尾递归优化,如何确保它?

推荐答案

可以支持不同级别的尾调用优化.JIT 真正负责任何 .NET 程序中的大部分优化.C# 编译器本身甚至不进行方法内联,这是 JIT 编译器的责任.C# 编译器可以使用 Tailcall IL 操作码 将调用指定为尾调用,但是我相信没有任何版本的 C# 编译器会这样做.JIT 编译器可以在它认为合适的时候进行尾调用优化.特别是,我相信只有 64 位 JIT 才能做到这一点.此博客文章概述了一个数字JIT64 无法使用尾调用优化的场景.我确信标准可能会发生变化,因为他们正在重写代号为 RyuJIT 的 JIT 编译器.

There are different levels at which the tail call optimization can be supported. The JIT is really responsible for most of the optimizations in any .NET program. The C# compiler itself doesn't even do method inlining, that is the JIT compiler's responsibility. The C# compiler could use the Tailcall IL opcode designating a call as a tail call, however I believe no version of C# compiler does this. The JIT compiler is permitted to make tail call optimizations whenever it sees fit. In particular, I believe only the 64-bit JIT does this. This blog post outlines a number of scenarios in which JIT64 cannot use tail call optimization. I'm sure the criteria may be subject to change since they are working on a rewrite of the JIT compiler, codenamed RyuJIT.

如果您想要一个可以使用 TCO 的程序的简短示例,试试这个:

If you want a short example of a program that can use TCO try this:

class Program
{
    static void Main(string[] args)
    {
        Test(1);
    }

    private static void Test(int i)
    {
        Console.WriteLine(i);
        Test(i + 1);
    }
}

将项目设置为构建 Release/x64(或 AnyCPU w/o 首选 32 位)并在不附加调试器的情况下启动.该程序将永远运行.如果我不做所有这些事情,那么我会在 20947 附近收到一个 stackoverflow 异常.

Set the project to build Release/x64 (or AnyCPU w/o prefer 32-bit) and start without the debugger attached. The program will run forever. If I do not do all of those things, then I get a stackoverflow exception around 20947.

这篇关于带有尾递归优化的 C# 编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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