Wednesday, April 25, 2012

Tail recursion

Some odd behavior to keep in mind.

The following code is expected to fail with StackOverflowException:


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

       private static void Tail()
       {
              Tail();
       }
}

And it actually fails in all build configuration, except "Release - x64". In this configuration .NET 4 enables the tail recursion optimization, so the Tail() function just hangs.


You can find more info about tail recursion optimization here.

2 comments:

  1. забавно, но в этом примере даже call-а нет. JIT скукоживает метод до одного jmp-а на самого себя.

    ReplyDelete
  2. Perhaps you might find it interesting: http://www.cs.indiana.edu/~dfried/mex.pdf

    I've read it just a couple days ago. In this talk, apart from a general discussion Friedman shows how one can transform a program to eliminate tail calls.

    ReplyDelete