I used the below two functions to test the Tail recursive optimization under MSVC08
int TailRecursively1(int i)
{
return TailRecursively1(i);
}
int TailRecursively2(std::string str)
{
return TailRecursively2(str);
}
why has TailRecursively1 been optimized, but TailRecursively2 has caused the stack overflow?
Tail call optimization happens when the compiler transforms a call immediately followed by a ret into a single jmp . This transformation saves one instruction, and more importantly it eliminates the implicit push/pop from the stack done by call and ret .
In tail recursion, there is no other operation to perform after executing the recursive function itself; the function can directly return the result of the recursive call. In simple words, in tail recursion, the recursive function is called last. So it is more efficient than non-tail recursion.
There are many problems where you are trying to do optimization. That is, you are attempting to find a way of doing something that maximizes or minimizes some quantity. A recursive divide and conquer approach is often successful for dealing with such problems.
Tail Recursion Elimination is a very interesting feature available in Functional Programming languages, like Haskell and Scala. It makes recursive function calls almost as fast as looping.
Because there are calls for std::string copy constructor and destructor when sending the str parameter by value to TailReucrsively2?
(I'm not 100% sure about this)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With