Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP-CLI - how to reduce memory usage required for starting up PHP process

When PHP process starts up, it loads extensions, various configuration directives and creates global / env variables and such, which (I assume) uses up memory.

What I'm aiming to do is to bootstrap a simple PHP script that uses the least amount of memory possible for doing a specific task.

An example CLI script such as:

printf("\nHello World");

The code above does not rely on any $_ENV variables or certain PHP streams that are open by default, which, if they weren't present - would make PHP process use less memory.

What would you guys do to reduce memory usage to minimum, in order to run the code outlined above?

like image 710
user2601913 Avatar asked Oct 20 '22 05:10

user2601913


1 Answers

For gaining a few bytes, you could run your PHP-Code in a clean environment:

env -i php -r 'var_dump(memory_get_peak_usage()); var_dump($GLOBALS);'

The env -i starts the script in a clean environment. You can see the difference by dumping the $GLOBALS. The function memory_get_peak_usage() shows the maximum consumed memory for the script. But on my system, I gain only a few KB with this method. It depends on your environment variables.

For a real optimization of the memory footprint, you have to look into your used extensions. To get your extension path, just execute a script like this:

php -r 'var_dump(ini_get("extension_dir"));'

You probably find some extensions like this:

curl.so
gd.so
json.so
[...]

These are the extensions you can load dynamically with dl(). They do not get into you memory usage. But if you like to see every extension loaded by the system, you can use the following command:

php -m

Comparing these lists, you will notice, there are much more extension available. These are compiled into PHP. To have a lower memory footprint, you would have to compile PHP from source.

To optimize PHP, you have to look into your code, which extensions you need. Getting the right options for ./configure is a time consuming task. For the beginning, see http://www.php.net/manual/de/configure.about.php

Usually, if you need a specific extension, you would go to the PHP-manual and take a look in the installation section for the extension, for zlib, this would be for example http://php.net/manual/de/zlib.installation.php

For your specific example you should try to compile PHP from source without options and test if it fulfills your needs.

like image 116
Trendfischer Avatar answered Oct 24 '22 11:10

Trendfischer