When and why does recursion perform worse than iteration?
I was recently asked this question for interview. My answer was recursion performs worse when the depth of recursion is large. The interviewer seemed to be expecting a different answer. Could anyone please explain it more.
preguntado el 01 de febrero de 12 a las 03:02
Could be many reasons; some that come to mind:
- The recursive depth is large increasing stack use - time is spent winding and unwinding the stack, and memory is consumed by the stack leaving less for each recursion, whereas iterating uses JUMP commands that do not use more resources (including the stack)
- The recursive function holds a lot of state (e.g. local variables) that must be kept in memory until the recursion is complete (iteration, on the other hand, throws away the locals with each iteration), again leaving less available memory for each subsequent recursion
From what you've stated, you have answered the When part of the question:
when the depth of recursion is large
but not the Why part, so you have only answered half of what the interviewer asked.