Blog

Thoughts from my daily grind

Recursion vs Iteration in Software Engineering

Posted by Ziyan Junaideen |Published: 24 March 2022 |Category: IT
Default Upload |

Recursion and iteration are used when we repeatedly need to execute a set of instructions. In recursion, we use a function within its definition, causing the repetition to occur. In contrast, we use loops in iterative design to execute repetitive tasks. The two approaches have their advantages and disadvantages.

Personally, I prefer recursion. I find recuse code easier to understand. That said, I wasn't always like this. When I was an undergraduate, I had found it difficult to implement even the easiest recursive functions. Ten years later, I prefer recursion over iteration. That said, I do always implement compute-heavy functions using iteration.

Recursion

  • Requires less code
  • Code turns out to be easy to follow and understand
  • Requires a base condition to break the recursion
  • Shortcomings in base condition can result in infinite repetition
  • Higher time complexity relative to iterative code
  • Large overhead w.r.t. iteration when it comes to computing and memory

Iteration

  • Requires more code to handle iteration
  • Could be implemented bounded (ex: posts.each { |post| ... })
  • Iteration can also be unbounded (ex: loop { ... })
  • Bonded iterations are less likely to end up in infinite loops unlike unbounded loops
  • Unounded loops, like recursion, require an exit condition (or break condition)
  • Code is more efficient w.r.t. recursive code

TODO

  • Examples
  • Benchmark
About the Author

Ziyan Junaideen -

Ziyan is an expert Ruby on Rails web developer with 8 years of experience specializing in SaaS applications. He spends his free time he writes blogs, drawing on his iPad, shoots photos.

Comments