bblue
bblue

Reputation: 553

Should I unset my PHP array values?

Does garbage collection on array values work like the garbage collection on normal variables?

I.e. will the complete $array be kept in memory until each array key is unset or the whole array no longer has a pointer to it, OR will PHP clean up the memory for an array key if it no longer has a reference to it?

I guess what I am asking is whether PHP deals with the array as one single variable garbage wise, or the actual pieces of the array.

Having a hard time explaining my question, hopefully this makes sense to someone:)

The reason for my question is that I am converting a potentially large result set from SQL into an array of PHP objects, and then filter this array. I might change my filtering functions somewhat dependent on the answers I get here.

Upvotes: 4

Views: 1368

Answers (1)

Sven
Sven

Reputation: 70863

It is a good idea to start unsetting variables if you know they use a lot of memory, like huge images, or big SQL query results, but only if you know for sure the info isn't needed anymore, and if your PHP complains about not having enough memory. Or your webserver. Freeing tiny parts of memory in the middle of a block of still used memory is useless. It won't be reused. And reordering the memory would eat performance. PHP is pretty optimized in dealing with variables.

Unsetting a variable will free it's memory if there is no other reference pointing to the value. This is true for an array as well: All array keys are references to their values, and if they are the only one, unsetting the array itself will unset all stored values inside.

You should know that query results are stored entirely in memory. You cannot access it directly, but there are functions like mysqli_result::data_seek() that will let you point to the entry you want to read, and the next call to mysqli_result::fetch_assoc() will get it.

If you are really copying the result to an array, you are at least doubling your memory consumption until you delete the query result (either explicitly with a call to mysqli_result::free(), or by unsetting the result object).

You could however also create a wrapper around the mysqli_result that implements the ArrayAccess interface (and probably also Iterator and Countable). This IS your array - without copying. An access to a random value would first call seek(), then fetch_assoc(), and return the value.

You then have the freedom to make use of all the SPL classes. Want to filter the result when running over it with foreach? Implement your own FilterIterator, put your result wrapper inside, and there you go.

Upvotes: 2

Related Questions