Why should recursion be preferred over iteration?

前端 未结 18 1199
既然无缘
既然无缘 2020-11-29 18:50

Iteration is more performant than recursion, right? Then why do some people opine that recursion is better (more elegant, in their words) than iteration? I really don\'t see

18条回答
  •  借酒劲吻你
    2020-11-29 19:31

    I would compare recursion with an explosive: you can reach big result in no time. But if you use it without cautions the result could be disastrous.

    I was impressed very much by proving of complexity for the recursion that calculates Fibonacci numbers here. Recursion in that case has complexity O((3/2)^n) while iteration just O(n). Calculation of n=46 with recursion written on c# takes half minute! Wow...

    IMHO recursion should be used only if nature of entities suited for recursion well (trees, syntax parsing, ...) and never because of aesthetic. Performance and resources consumption of any "divine" recursive code need to be scrutinized.

提交回复
热议问题