Page 1 of 1

Does mysql result mem get freed at the end of a function ?

Posted: Tue Aug 28, 2007 10:56 am
by anjanesh
Hi

Its mentioned in docs about mysql_free_result that
All associated result memory is automatically freed at the end of the script's execution.
But does it get freed at the end of a function

Code: Select all

function foo()
 {
        $res = mysql_query($sql)
        .
        .
        .
        mysql_free_result($res) # Does $res's content still exist in memory even though $res is out of scope ?
 }
Thanks

Posted: Tue Aug 28, 2007 11:13 am
by RobertGonzalez
No, it gets freed when either A) you directly call mysql_free_result; or B) the database connection is closed; or C) The script execution stops.

Posted: Tue Aug 28, 2007 11:18 am
by anjanesh

Code: Select all

function foo1()
 {
        $res = mysql_query($sql)
        .
        .
        .
        return
 }
function foo2()
 {
        $res = mysql_query($sql)
        .
        .
        .
        return
 }

 .
 .
 .
So the unused result-resource after a function call keeps building up in memory or gets overwritten on the next query ?

Posted: Tue Aug 28, 2007 11:55 am
by RobertGonzalez
I believe the buffer is overwritten.

Posted: Tue Aug 28, 2007 1:05 pm
by AKA Panama Jack
anjanesh wrote:

Code: Select all

function foo1()
 {
        $res = mysql_query($sql)
        .
        .
        .
        return
 }
function foo2()
 {
        $res = mysql_query($sql)
        .
        .
        .
        return
 }

 .
 .
 .
So the unused result-resource after a function call keeps building up in memory or gets overwritten on the next query ?
It depends upon the version of PHP. Some versions of PHP do stack the result sets and don't overwrite so you keep using more and more memory. Certain older versions of PHP 4 wouldn't clear connections when the PHP script ended either. The BEST coding practice with any database under PHP is to close and free the resultset as soon as you are FINISHED with it.

In the game listed in my signature, the scheduler can process anywhere from a hundred to a few thousand queries every 5 minutes. Even though we reused resultsets a lot of memory would be used at times. It wasn't until we closed each query with a mysql_free_result when we were finished with the data from that query that memory usage stopped going up.

It's just good programming practice to close and free your resultsets. The same thing on connections. Don't rely on PHP doing everything for you. It's just lazy.

Posted: Tue Aug 28, 2007 1:24 pm
by thewebdrivers
best to use mysql_free_result

Posted: Tue Aug 28, 2007 1:27 pm
by anjanesh
What abt mysqli ?
Is it more efficient in releasing resources ?

Posted: Tue Aug 28, 2007 1:29 pm
by AKA Panama Jack
You will still need to use the free_result for Mysqli if you want to efficiently release memory used by any returned resultsets from queries.