C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: The recursive method X will be called 11 times total. On the last call, it does not enter the inner if-statement block.
C# program that uses recursive method
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// ... Call recursive method directly.
List<int> list = new List<int>();
X(list, 0);
// ... Verify sum.
Console.WriteLine(list.Sum());
}
static void X(List<int> list, int value)
{
if (list.Count < 10)
{
list.Add(value);
X(list, value + 1);
}
}
}
Output
45
Tip: One option is still available. We can take the method body from the recursive method X and paste it into the Main method.
Info: Obviously, we cannot force the compiler to completely inline a recursive method.
Here: This program reduces the calls to the X method by 1. It also reduces the stack depth by 1 frame.
C# program that inlines recursive call
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// ... Inline first recursive call.
List<int> list = new List<int>();
if (list.Count < 10)
{
list.Add(0);
X(list, 0 + 1);
}
// ... Verify sum.
Console.WriteLine(list.Sum());
}
static void X(List<int> list, int value)
{
if (list.Count < 10)
{
list.Add(value);
X(list, value + 1);
}
}
}
Output
45
And: This option basically enabled the impossible. It let us inline a recursive method that could not be tail-optimized.
Info: Method call depth is relevant to performance. A shallower stack frame is faster.
Method Call Depth Performance