Recursion or Iteration?

前端 未结 30 2414
小鲜肉
小鲜肉 2020-11-22 14:44

Is there a performance hit if we use a loop instead of recursion or vice versa in algorithms where both can serve the same purpose? Eg: Check if the given string is a palind

30条回答
  •  孤城傲影
    2020-11-22 15:12

    In C++ if the recursive function is a templated one, then the compiler has more chance to optimize it, as all the type deduction and function instantiations will occur in compile time. Modern compilers can also inline the function if possible. So if one uses optimization flags like -O3 or -O2 in g++, then recursions may have the chance to be faster than iterations. In iterative codes, the compiler gets less chance to optimize it, as it is already in the more or less optimal state (if written well enough).

    In my case, I was trying to implement matrix exponentiation by squaring using Armadillo matrix objects, in both recursive and iterative way. The algorithm can be found here... https://en.wikipedia.org/wiki/Exponentiation_by_squaring. My functions were templated and I have calculated 1,000,000 12x12 matrices raised to the power 10. I got the following result:

    iterative + optimisation flag -O3 -> 2.79.. sec
    recursive + optimisation flag -O3 -> 1.32.. sec
    
    iterative + No-optimisation flag  -> 2.83.. sec
    recursive + No-optimisation flag  -> 4.15.. sec
    

    These results have been obtained using gcc-4.8 with c++11 flag (-std=c++11) and Armadillo 6.1 with Intel mkl. Intel compiler also shows similar results.

提交回复
热议问题