DEV Community

Brainvault Technologies
Brainvault Technologies

Posted on

UNDERSTANDING MEMORY USAGE: INSIGHTS ON RECURSION AND DO WHILE LOOPS

Introduction

As a Software Engineer, I prioritize code that's not only functional but also mindful.This article explores the memory management implications of recursion compared to do-while loops. While recursion excels in solving problems with inherent recursive structures, it can lead to memory exhaustion when dealing with large datasets. Here, we'll see how do-while loops offer a more memory-efficient alternative in specific scenarios.

Loops and Recursion: Powerful Tools - Why?

Programming is all about automation and efficiency. Loops and recursion are two fundamental techniques that help us achieve this. Let's delve into each concept and explore more about loops and recursion.

Loops: The Workhorses of Repetition

Loops are essential tools for executing a block of code repeatedly until a specific condition is met. They come in various flavors, each with its own strengths:

For loops: Ideal when you know exactly how many times you need to iterate, often used with counters.

  • While loops: Continue executing the code block as long as a certain condition remains true, useful for user input validation or searching for specific elements.
  • Do-while loops: Similar to while loops, but guarantee at least one execution of the code block, even if the condition is initially false.
  • These loops excel at automating repetitive tasks, processing data collections, and controlling program flow.

Recursion: A Powerful Technique for Recursive Problems

Recursion is a programming concept where a function calls itself. This can be a very elegant and concise way to solve problems that have an inherently recursive structure, like:

Tree traversals: Recursively visiting each node in a tree data structure.

  • Divide-and-conquer algorithms: Breaking down a complex problem into smaller, similar subproblems.
  • Factorials or Fibonacci sequences: Calculating these values often involves calling the function with a smaller input.
  • While recursion offers a clean and sometimes intuitive solution, it comes with a caveat – memory usage.

Image description
The Problem with Recursion

Recursion is a powerful programming technique. Especially while studying DSA or solving LeetCode problems.

It is great if you work with an object mostly (self) or when you traverse an existing data. It involves functions calling themselves. Here each recursive call creates a new frame on the call stack, which stores local variables and function arguments. When dealing with large datasets or deep recursion, these ever-growing call stacks can consume significant memory, potentially leading to stack overflows or memory exhaustion errors.

Example: Consider that you are about to call an api in a recursive method and it might get called at least 10 times. Each time the API returns 1MB of data. So at the end of the recursive method, the memory usage would be 10*1MB = 10MB.

Consider the following example fetching paginated data from an API:



protected function getData(int $page_no = 1) {
  $data = Http::get('users', ['page' => $page_no]);

  // Process the data

  if ($data['hasMore']) {
    return $this->getData($page_no + 1);
  }
}


Enter fullscreen mode Exit fullscreen mode

In this recursive approach, a new $data variable is created for each API call. If the data is large and requires multiple page fetches, the memory usage can quickly climb due to the accumulation of these variables on the call stack.
Do-While Loop - More appealing method
Do-while loop acts as an alternative method for iterating through data where the condition is checked at the beginning. Do.While can override the existing variable if any of them exist already. So that it won't allocate new memory each time. Unlike recursion, do-while loops reuse the same variable throughout the loop, avoiding the creation of new variables on each iteration.
Here's a rewritten version using a do-while loop:



protected function getData(int $page_no = 1) {
do {
$data = Http::get('users', ['page' => $page_no]);
// Process the data
} while ($data['hasMore']);
}


Enter fullscreen mode Exit fullscreen mode

In this do-while loop, the $data variable is used consistently, and its memory allocation is overwritten on each loop iteration. This significantly reduces memory consumption compared to the recursive approach.
Readability and Maintainability
Beyond memory efficiency, do-while loops can sometimes enhance code readability, especially for simpler tasks like iterating through paginated data. Their straightforward structure can make them easier to understand and maintain for programmers less familiar with recursion.
When Recursion Still Reigns Supreme
Recursion remains a valuable tool. It excels when dealing with problems that exhibit a naturally recursive structure, such as tree traversals or divide-and-conquer algorithms. In these cases, recursive solutions can often lead to more elegant and concise code compared to iterative approaches.
Conclusion
It’s not like recursion is useless and do- while is more suitable. There is always more than a single way to approach a problem statement. While in this case, we can use recursion also by clearing /freeing the data allocated using the unset function. But I feel that this is one of the use cases for Do While and wanted to share my insights on it. From my point of view I find Do While more readable and suitable.

About us

As a Software Engineer working at Brainvault Technologies, I strongly believe in the power of collaborative innovation. BrainVault Technologies emerges as a pioneering force, driving innovations set to redefine our interaction with technology. Together, we embark on a thrilling adventure brimming with endless possibilities to boost efficiency. I hope this comprehensive exploration of loops and recursion has been valuable! By understanding their strengths and weaknesses, you can make informed decisions about which technique best suits your programming needs.

If you'd like to delve deeper into specific aspects of loops or recursion, feel free to leave a comment below or Connect with me on linkedin: https://www.linkedin.com/in/praem90/
I'd be happy to assist further!
I'm always eager to learn and collaborate on programming topics. Let's continue exploring the fascinating world of code together!

Author Credits: Mohan Raj — Software Engineer

Top comments (0)