We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Tiny(?) memory leak

Hey guys. Before creating an issue on github, I wanted to consult you on a possible memory leak I found.

Use case

AWS opened AWS Lambda to support custom platforms, so I wanted to see whether I could get our phalcon application to work. The basic idea of running php in Lambda is that there is a long-running php process with a loop processing requests coming to Lambda, similar to a message queue worker.

The issue

Inside the mentioned loop, the application itself is running. However, I quickly noticed that the Lambda ran out of memory. After reconstructing the setup locally, I noticed that every iteration of bootstrapping phalcon increased the memory usage.

Example

<?php
$oldUsage = 0;

for($i=0; $i<10; $i++) {
    $app = new \Phalcon\Mvc\Micro();
    $app->get(
        '/',
        function () {
        }
    );

    $app->handle();
    //gc_collect_cycles();

    $usage = memory_get_usage() / 1024;
    $diff = $usage - $oldUsage;
    $oldUsage = $usage;
    echo $diff . 'kb<br />';
}

PHP 7.2.20, Phalcon 3.4.4 On my machine, this adds around 8kb of memory every iteration. Adding gc_collect_cycles() reduces this amount to 0.03kb, but with a more complex application, this amount increases significantly.

Do you have any ideas how to solve this, or should I simply report a bug on github?

edited Aug '19

Hi I would ask as first, why you creating new instance of app, every loop ? Is that really needed ? Put the definition of $app and $app->get out of the loop, and call only $app->handle() in the loop and try if the memory will be still increasing.

Haven't tried that, yet but that would be my first suggestion to do as that's first what I can see

Out of loop:

412.046875kb

0.03125kb
0.03125kb
0.03125kb
0.03125kb
0.03125kb
0.03125kb
0.03125kb
0.03125kb
0.03125kb

Out of loop also using gc_collect_cycles() tested in console php test.php

393.796875kb
0.03125kb
0kb
0kb
0kb
0kb
0kb
0kb

In loop:

412.046875kb

8.3671875kb
8.3671875kb
8.3671875kb
8.3671875kb
8.3671875kb
8.3671875kb
8.3671875kb
8.3671875kb
8.3671875kb

Also be aware of circular referencing, as that's something for PHP hard to release, good example is ( Doctrine ), it's using circular references.

I guess you can try report it with valgrind report/log