We are using recursion to find factors and are receiving a StackOverflow exception. We've read that the C# compiler on x64 computers performs tail call optimizations:
JIT definitely does tailcals when running optimized code and not debugging.
Running dotnet --configuration release
gets this far in our program:
...
7214 is a factor of 1234567890
7606 is a factor of 1234567890
10821 is a factor of 1234567890
11409 is a factor of 1234567890
Process is terminated due to StackOverflowException.
Why is tail call optimization not occuring?
class Program
{
static void Main(string[] args)
{
const long firstCandidate = 1;
WriteAllFactors(1234567890, firstCandidate);
}
private static void WriteAllFactors(long number, long candidate)
{
if (number % candidate == 0)
{
System.Console.WriteLine($"{candidate} is a factor of {number}");
}
candidate = candidate + 1;
if(candidate > number / 2)
{
return;
}
WriteAllFactors(number, candidate);
}
}
VSadov provides the explicit reason for this in his response:
In addition, he goes on to state:
So the answer is that while tailcalls are definitely available and used, there is no way to either predict when they will be used or force them to be used in C#.