您的位置:首页 > Web前端

What are some of the differences between using recursion to solve a problem versus using iteration?

2016-01-06 23:13 471 查看
The fact is that recursion is rarely the most efficient approach to solving a problem, and iteration is almost always more efficient. This is because there is usually more overhead associated with making recursive calls due to the fact that the call stack is
so heavily used during recursion (for a refresher on this, read here: Recursion tutorial).
This means that many computer programming languages will spend more time maintaining the call stack then they will actually performing the necessary calculations.

Does recursion use more memory than iteration?

Generally speaking, yes it does. This is because of the extensive use of the call stack.

Should I use recursion or iteration?

Recursion is generally used because of the fact that it is simpler to implement, and it is usually more ‘elegant’ than iterative solutions. Remember that anything that’s done in recursion can also be done iteratively, but with recursion there is generally a
performance drawback. But, depending on the problem that you are trying to solve, that performance drawback can be very insignificant – in which case it makes sense to use recursion. With recursion, you also get the added benefit that other programmers can
more easily understand your code – which is always a good thing to have.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: