fomo-framework / fomo

A simple, fast framework with many features for the HTTP
MIT License
147 stars 12 forks source link

Use static variable and performance suggestion #10

Closed vanthuanqs closed 4 months ago

vanthuanqs commented 1 year ago

First, I want to say thank you for awesome framework.

I have been working around the framework and I see that in response() function, whenever you call it, it create a new object from Response class. I don't think it's really needed since in one life cycle of a HTTP request, we need only one object of Response

I create a response_intance() function:

function response_instance(): Response
{
    static $responseInstance;
    if (is_null($responseInstance)) {
        $responseInstance = response();
    }

    return $responseInstance;
}

I also tested the performance:

$starttime = microtime(true);
for ($i = 0; $i < 10 * 1000 * 1000; $i++) {
    response_instance();
}
echo "response_instance() time : ", (microtime(true) - $starttime), " ms\n";

$starttime = microtime(true);
for ($i = 0; $i < 10 * 1000 * 1000; $i++) {
    response();
}
echo "response() time : ", (microtime(true) - $starttime), " ms\n";

and the result:

response_instance() time : 0.28365898132324 ms
response() time : 2.3586940765381 ms

It's much more faster than create new object every time you call the function So I think we better create only one instance for these types of variables, example Request, Cache, ...

amirfaramarzi commented 1 year ago

Hi

I am very happy for your cooperation

I wanted to do this request before, but I didn't get the chance. I will be very happy if you create this pull request.

amirfaramarzi commented 4 months ago

Hi @vanthuanqs,

The announced feature is now available 🔥