Skip to content

Optimization: Tail Recursion #8

@mkaring

Description

@mkaring

While generally something that always should be avoided, tail recursions are something that is written every now and then in the code.

Detecting and optimizing this is relatively easy. There are in general two ways to optimize a tail recursion when it is written in C# or VB.

  1. Adding the TailCall instruction before the return. This will clear out all memory preserved on the stack before moving on to the next iteration of the function. The upside of this method is that the stack depth behaves the same way as the original version.
  2. Adding a loop to the method instead of the recursive call. This is the solution everyone should write in the first place. The only disadvantage is that the stack behaves differently, compared to the original version.

Both method should be supported. Adding the TailCall should be the default option, as it just causes the stack memory to be discarded before the resursive invoke.

In case the method that calls itself recursively is virtual, only the first option is relevant, because the invocation may cause another implementation of the method to be called.

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions