Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is pg_free_result() necessary, even if the result goes out of scope?

The PHP docs have this to say about pg_free_result():

This function need only be called if memory consumption during script execution is a problem. Otherwise, all result memory will be automatically freed when the script ends.

http://www.php.net/manual/en/function.pg-free-result.php

I would (perhaps naively) have expected the resource returned by a call to pg_query() to be garbage collected when it goes out of scope.

In a hypothetical function like this:

function selectSomething ()
{
    $res = pg_query("SELECT blah FROM sometable");
    // do something with $res
    pg_free_result($res);   // required or not?
}

Is it really necessary to call pg_free_result() at the end?

In other words, if I call this function 1000 times, will it eat up memory to store all 1000 results?

EDIT: I'm talking about the typical case, i.e. pg_connect() instead of pg_pconnect().

like image 349
Zilk Avatar asked May 14 '13 22:05

Zilk


1 Answers

As Elias Van Ootegem rightly indicates you are almost certainly using a persistent connection. With persistent connections after the query the result must continue in memory because you may wish to gather more data from it (for example the last error).

So it comes down to good practice. If you are operating in an environment where you have 2M of available memory and your script can, at times, hit up to 0.1M of memory then the upper limit is 20 concurrent connections calling that script. After that further web requests are going to queue or drop. It doesn't take a genius to realise how vulnerable this might be to DDoS attack.

Best practice, then, is to empty memory just as soon as you are done with it. This goes for just about any programming or scripting ever. When the system is being stressed and demand is high the more requests that can be serviced inside the total scope of memory the better. If you can lower the maximum memory footprint of a script you can increase the number of concurrent connections that can reasonably try to call it and thus increase the load the script can handle.

The ideal way to do things is to release resources as soon as you can. Just because we don't and everything seems to work anyway during testing is no reason not to.

like image 84
Matthew Brown aka Lord Matt Avatar answered Nov 15 '22 04:11

Matthew Brown aka Lord Matt