简体   繁体   中英

Freeing up memory in php script

I have finished writing my php scripts for a project I am doing. My next step is I would like to see if I can improve my code from a memory stand point as some of my scripts eat a lot of memory. I have been doing research on this and one suggestion is to NULL and unset variables, but I never see an example of doing this. So I wanted to give an example of a common action done in my scripts and wanted to know if this is the proper way of doing this:

    $query = $dbconn->get_results("SELECT id,name FROM account WHERE active = 1");

    if(isset($query))
    {

    foreach($query AS $currq)
    {

    $account_id = intval($currq->id);
    $account_name = trim($currq->name);

    //Code to stuff with this data

    //NULL the variables before looping again
    $account_id = NULL;
    $account_name = NULL;

    //Unset the variables before looping again
    unset($account_id);
    unset($account_name);

    }

$query = NULL;
unset($query);

$currq = NULL;
unset($currq);

Would that be the correct way to free up memory? I read the garbage collection in PHP can be lazy, so that is why they recommend to NULL the value as it will shrink it right away.

I know this might be too vague for this site, but if anyone can just let me know if this is the proper way of freeing up memory? Or if there is a different way, can you please provide an example just so I can visually see how it work. Thanks in advance!

Please read up on PHP generators , that is what they are exactly for.

You don't want to fetch all records at once, this would blow holes into your memory like a shotgun.

Instead you want to fetch your records one at the time, process it then fetch the next one.

Here is an example:

function getAccountData(\PDO $pdo)
{
    $stmt = $pdo->prepare("SELECT id,name FROM account WHERE active = 1");
    $stmt->execute();

    while ($row = $stmt->fetch()) {
        yield $row;
    }
}



foreach (getAccountData($pdo) as $account){
    //process the record for each iteration
    //no need to unset anything
}

Well, if the function $dbconn->get_results returns an array with all the data, then there is no point in using generators since the memory has already being allocated for the data.

You can also use the mysqli_fetch_assoc function to get one row at a time. It should be more memory efficient then fetching all rows at once. http://php.net/manual/en/mysqli-result.fetch-assoc.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM