Iterating an associative array without using a foreach loop and fixing memory leaks

I am developing a command line script that runs in an infinite loop. After some time, it causes a segmentation error, which, it seems to me, is caused by memory leaks. I think I'm right, because after looking at the results obtained by the ps command, it looks like the memory used by the script is constantly increasing before the script crashes.

I found this article which says that one of the possible causes of a memory leak on the php command line is to use foreach loops that create copies of arrays that never get disconnected. After some research, it looks like this. So I decided to replace all foreach loops with their for equivalents.

The first question is whether I am reasoning correctly.

Second - what if I have an associative array to iterate and I would like to know the current key?

One way I can think of is to use array_walk() , the other is to use a combination of the next() and key() functions in a for loop. Which approach would not leave me with memory leaks?

I will conduct some tests and publish the results after I do.

A secondary problem is how to handle iterable objects, but for later versions.

EDIT 1 . There are some excellent results from my tests, so I will post something new after several studies.

+4
source share
1 answer

Using next () and key () will not give you the memory leaks that foreach does. Foreach creates an β€œinternal” copy of your array, and this copy is a memory leak problem. Using next () and key () does not create a copy - then you are working with the source data.

Another suggestion on how to solve this is to use array_keys () as follows:

 $keys = array_keys($assoc_array); for ($keyindex = 0; $keyindex < count($keys); $keyindex++) { $key = $keys[$keyindex]; $val = $assoc_array[$key]; /* Now you have $key and $val. */ } 

However, I believe that your suggestion using next () and key () will be most effective - and will probably also give you the most beautiful code! :)

+1
source

Source: https://habr.com/ru/post/1402845/


All Articles