¿Cuándo y por qué la recursividad funciona peor que la iteración? [cerrado]

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

Perhaps they were expecting the answer that premature optimization is a waste of time, that you should write code that is clear and understandable and only optimize if it's demonstrated to be an actual bottleneck. You can come up with some great theoretical answers either way, but ultimately, all of them are irrelevant in the real world. -

Perhaps she wanted you to talk about tail recursion optimization? stackoverflow.com/questions/491376/… -

Recursion: The absolute fastest way to a stackoverflow.com/questions/9090339/… -

That one gives you the reason. Leer La respuesta de paul again, carefully this time. Note the links. -

2 Respuestas

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

Respondido 01 Feb 12, 07:02

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.

Respondido 01 Feb 12, 07:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.