sami_analyst
sami_analyst

Reputation: 1839

cant free up memory by creating and unseting object in for loop

Im running a loop which creates an object (where some arrays get created) and unseting it afterwards right in the loop:

private function _runLoop($amountPerStep = 4){
    $steps = floor(count($this->_symbolRows)/$amountPerStep);
    $echo = "";
    for($i = 0; $i <= $steps; $i++){
        $tempSymbolRows = array_slice($this->_symbolRows,$i*$amountPerStep,($i+1)*$amountPerStep);
        if (count($tempSymbolRows) == 0) continue;
        $tempSymbols    = array();
        for($j = 0; $j < count($tempSymbolRows); $j++){
            $tempSymbols[] = $tempSymbolRows[$j][0];
        }
        $scrapping = new Scraping($tempSymbols);
        $echo .= "<pre>";
        $echo .= "memory_peak_usage / memory_usage <br/>";
        $echo .= memory_get_peak_usage()/1000000 ." / ". memory_get_usage() / 1000000 ."<br/><br/>";
        //print_r($scrapping->getArrays());
        $echo .= "</pre>";
        $scrapping = NULL;
        unset($scrapping);
        gc_collect_cycles();
        if( $i >= 3 ) break;
    }
    echo $echo;
}

after the third running in the lop im breaking the loop (testing purposes). i commented out the line where i print the arrays of the loop because it would eat up memory by saving the arrays for the print (even the object is not existing). thought that would be the problem. but when i run the loop i get this output

memory_peak_usage / memory_usage 
7.805928 / 1.530504

memory_peak_usage / memory_usage 
9.723464 / 6.28792

memory_peak_usage / memory_usage 
39.414088 / 17.227368

memory_peak_usage / memory_usage 
55.541584 / 23.166608

so the used memory size is getting bigger and bigger ... where is the mistake ? why does the gc not freeing up ressources ?

Upvotes: 0

Views: 225

Answers (1)

Jim
Jim

Reputation: 22656

Taken from the discussion in the comments.

$tempSymbolRows = array_slice($this->_symbolRows,$i*$amountPerStep,($i+1)*$amountPerStep);

This line creates a larger array each loop since the third argument to array_splice is not an offset. This causes an increase in memory use.

Upvotes: 2

Related Questions