Decrease memory usage of recursive functions in PHP

Asked

Viewed 154 times

0

I have a recursive function in PHP where it loops into an api where it only allows you to retrieve 200 records at a time.

However as this API has a very high response latency we decided to use a local intermediate database where I add these records and the same will be shown on the site.

But since this API has more than 30,000 records the recursive function it consumes a lot of memory because in the case of 30,000 records it would have to be recursively invoked more than 1500 times and this ends up giving the famous Stackoverflow.

I wonder if there is a manual way to clear the memory of this function calling it again without losing the value of it.

Code example:

public function recursive($index = 0, $offset = 200){
   $api = getConectApi($index,offset)->getRecords();
   foreach($api as $value){
      //aqui ocorre meu loop necessário
   }
   if(count($api) > 0){
     $this->recursive($index+200,$offset+200);
   }
}

I would like to find a way that when calling the recursive function again eliminates the previous allocation without losing the reference value that was passed.

  • 2

    I think there’s no way, you’ll have to come up with an iterative form.

  • I see, what you suggest to me?

  • 2

    Move to iterative form.

  • How the interactive way would work?

  • 2

    It would be no recursion. Now, to write code iteratively, we would need to know logic (your code in the question has only one comment where logic occurs).

1 answer

1


Browser other questions tagged

You are not signed in. Login or sign up in order to post.