c++compiler-optimization

C++ iterative vs recursion optimizations in the compiler


Let's say I have a recursive function that calls itself many times (like a factorial) before it ever reaches the base case/gets a value to start unrolling the rest up the chain. Will the compiler optimize this to the same code as if i were to write that function in iterative format?


Solution

  • The answer to this is "maybe". But if you really want to MAKE SURE the compiler doesn't make the function actually recursive, then you have to write it iteratively.

    Many compilers can detect "tail-recursion" and convert it to a loop. But not always, and not always with the same efficiency as if you wrote it yourself as an iterative function.

    For more complex cases, such as Fibonacci series (which is not a simple tail recursive function), it's often hard for the compiler to actually realize what is going on, and it has to resort to actually making it recursive, even tho' it is quite trivial to make it iterative. [When I tried fibonacci in recursive method, my results were MUCH worse than the iterative method - indicating that the compiler didn't solve it - and that's using gcc which is usually fairly clever on these things].