Free memory in php

0

Is it possible to free memory in PHP? In a method I execute some functions between them a foreach and after that I finish wanted to free memory.

I'm giving unset some variables but it does not retrieve the space again.

Is it possible?

Edit I will explain my intention to free the memory:

In the system I'm developing, I need to return details of a period that can go up to 1 year. Showing day by day the status of each block of time, with one day having up to 96 blocks.

Part of this code is a method that returns an array containing some of this detail.

And this code is consuming about 50 megs ... See the code:

public function getRenovacao($grades_id, $periodo_inicio, $periodo_fim, $atividades_comerciais_id) {

        Controller::startTest();
        Controller::checkPointStartTest('Laço While');

        $end_timestamp = strtotime($periodo_fim);
        $tmp_timestamp = strtotime($periodo_inicio);
        while ($tmp_timestamp <= $end_timestamp) {
            $tmp_dia_semana = (int) date("w", $tmp_timestamp);
            $tmp_data = date("Y-m-d", $tmp_timestamp);
            $periodo_array[$tmp_dia_semana][$tmp_data] = ['atividade_comercial_utilizada' => 0, 'duracao_utilizada' => 0];
            $tmp_timestamp = strtotime("+1 day", $tmp_timestamp);
        }

        Controller::checkPointEndTest();
        Controller::checkPointStartTest('Consulta banco de dados tabela "Blocos"');
        $select = 
                [
                    'blocos.grades_id',
                    'blocos.bloco',
                    'blocos.dia_semana',
                    'blocos.duracao',
                    'blocos_produtos.blocos_id',
                    'blocos_produtos.produtos_id',
                ];

        $grade_blocos = DB::table('blocos')
                ->join('blocos_produtos', 'blocos.id', '=', 'blocos_produtos.blocos_id')
                ->select($select)
                ->where('blocos.grades_id', $grades_id)
                ->get();

        $grade_blocos = json_decode(json_encode($grade_blocos),1);

        foreach ($grade_blocos as $dados) {
            if(array_key_exists($dados['dia_semana'], $periodo_array)){
                $key = (int)$dados['blocos_id'];
                $blocos[] = $dados['blocos_id'];
                $tmp_grade_blocos[$key]['id'] = $dados['blocos_id'];
                $tmp_grade_blocos[$key]['grades_id'] = $dados['grades_id'];
                $tmp_grade_blocos[$key]['bloco'] = $dados['bloco'];
                $tmp_grade_blocos[$key]['dia_semana'] = $dados['dia_semana'];
                $tmp_grade_blocos[$key]['duracao'] = $dados['duracao'];
                $tmp_grade_blocos[$key]['produtos'][] = $dados['produtos_id'];
                $tmp_grade_blocos[$key]['programacao'] = $periodo_array[$dados['dia_semana']];
            }
        }
        $grade_blocos = array_values($tmp_grade_blocos);
        $blocos = array_unique($blocos);

        unset($periodo_array, $tmp_grade_blocos, $tmp_data, $tmp_dia_semana, $tmp_timestamp,$end_timestamp);

        Controller::checkPointEndTest();
        Controller::checkPointStartTest('Consulta banco de dados tabela "Comerciais"');


        $blocos_tempo = DB::table('comerciais')
                ->join('produtos', 'comerciais.produtos_id', '=', 'produtos.id')
                ->select('blocos_id', 'atividades_comerciais_id', 'data', 'produtos.duracao')
                ->whereIn('blocos_id', $blocos)
                ->where('data', '>=', $periodo_inicio)
                ->where('data', '<=', $periodo_fim)
                ->get();

        Controller::checkPointEndTest();
        Controller::checkPointStartTest('Laço Foreach Final');

        foreach ($blocos_tempo as $dados) {
            $id = $dados->blocos_id;
            $grade_blocos_id = array_search($id, array_column($grade_blocos, 'id'));

            $tmp_data = $dados->data;
            $tmp_atividades = (int)$grade_blocos[$grade_blocos_id]["programacao"][$tmp_data]['atividade_comercial_utilizada'];
            if($dados->atividades_comerciais_id == $atividades_comerciais_id){
                $tmp_atividades++; 
            }

            $tmp_duracao_utilizada = (int)$grade_blocos[$grade_blocos_id]["programacao"][$tmp_data]['duracao_utilizada'] + (int)$dados->duracao;
            $grade_blocos[$grade_blocos_id]["programacao"][$tmp_data] =
                                                                        [
                                                                            'atividade_comercial_utilizada' => $tmp_atividades,
                                                                            'duracao_utilizada' => $tmp_duracao_utilizada
                                                                        ];
        }

        Controller::checkPointEndTest();
        Controller::endTest();
        //die();
        $return['grades_id'] = $grades_id;
        $return['blocos'] = $grade_blocos;

  

While loop       -------------------------------------------------- ---       Execution time: 0.00576 s.       Initial memory: 9.25 MB.       Final Memory: 9.5 MB.       Memory Used: 0.25 MB.       -------------------------------------------------- ---

Consulta banco de dados tabela "Blocos"
-----------------------------------------------------
Tempo de execução: 0.0788 s.
Memoria inicial: 9.5 MB.
Memoria Final: 18.75 MB.
Memoria Utilizada: 9.25 MB.
-----------------------------------------------------

Consulta banco de dados tabela "Comerciais"
-----------------------------------------------------
Tempo de execução: 0.54036 s.
Memoria inicial: 18.75 MB.
Memoria Final: 49 MB.
Memoria Utilizada: 30.25 MB.
-----------------------------------------------------

Laço Foreach Final
-----------------------------------------------------
Tempo de execução: 2.20804 s.
Memoria inicial: 49 MB.
Memoria Final: 50.25 MB.
Memoria Utilizada: 1.25 MB.
-----------------------------------------------------

TEMPO TOTAL DE EXECUÇÃO DO SCRIPT
-----------------------------------------------------
Tempo de execução: 2.83315 s.
Memoria inicial: 9.25 MB.
Memoria Final: 50.25 MB.
Memoria Utilizada: 41 MB.
----------------------------------------------------
    
asked by anonymous 07.07.2017 / 03:28

1 answer

1

Daniel does not have to worry about the php memory release he manages this. In reality when a nighx apache or lighttpd theards runs it runs php as a child that executes its php routines at the end of execution the return is returned to the http server and printed on the page and the server itself reuses the open php head to perform other requests that are arriving on the server. Or if there is no need to terminate the open theards to release memory usage this process is called GARBAGE COLLECTOR.

The command:

  

unset

Only if you want to release the value of a variable to reuse it in your script.

PS: theards = processing head.

This is a very superficial explanation of the way there are several ways to run php as cgi, fastcgi for example, if you want to delve into google ways to run php on apache or any web server.

I'll give you several solutions the first one is to debug to see the problem:

copy your COMMERCIALS table and enter another name then delete most of its contents as well as the records that relate to this table then edit your code to the new name of the tables and execute your routine. If you see the time plummeting it will detect where the execution bottleneck is, it's simple:

Solution 1: Partition the table

Solution 2: Create a new table and "pre-execute" the data of this join with stored procedure and create an event in the database to be running in the background updates, when executing your query run through this new table a simple query

Solution 3: I have never used it but I know there is a use view.

It's still a matter of making sure that your sql is right, as it uses a container class I had no way to analyze the construction of the query.

I hope this information is useful.

    
07.07.2017 / 04:56