Recursion level in C# vs F#

Interesting comparison between C# and F#: max level of recursion (on 64 bit machine).

C#:

class Program
{
    static void Main()
    {
        CheckRecursion(0);
    }

    public static void CheckRecursion(int val)
    {
        Console.WriteLine("Recursion level: {0}", val);
        CheckRecursion(val + 1);
    }
}

Result: 39925 depth level, and we have StackOverflowException

F#:

let rec checkRecursion(n) =
    printfn "%d" n
    checkRecursion(n+1)

checkRecursion(0)

Result: 16221946 depth level and program is still working 😉

For me, really awesome.

Results are connected with how F# is dealing with recursion code. More details about that, in the near future. Just worth to remember, if you have a problem with recursion and still need code like that, try to use F# code 🙂

Advertisements

One thought on “Recursion level in C# vs F#

  1. It’s really the question of how much memory you have on the machine for the stack, With 8GB I went down to over 1,6 M with simple recursion and hit CTRL-C as I didn’t have time to wait :). Of course tail recursion will always be more effective as it’s almost similar to looping. But the real issue here is – if you need even 39k iteration – there’s your problem 🙂 At least in normal apps.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s