Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minimizing PHP memory usage at script start

Tags:

php

memory

I have a script, that gets data send (about 16MB in size), which I read using php://input.

$in = file_get_contents("php://input");

But I'm running into memory limit issues, so I traced it down using memory_get_usage() and realized, that the script is already consuming 47MB memory on startup (before issuing any command).

My guess is, this is due to PHP pre-filing global variables. So I'm searching for a way to unset those, since I'm only reading the php://input stream.

I tried:

unset($GLOBALS);
unset($_SERVER);
unset($_GET);
unset($_POST);
unset($_FILES);
unset($_REQUEST);
unset($_ENV);
unset($_COOKIE);
unset($HTTP_RAW_POST_DATA);
unset($http_response_header);
unset($argc);
unset($argv);
gc_collect_cycles();

And it reduces the memory usage from 47MB to 31MB.

Is there anything else I can do, to have PHP consume less memory on startup?

It would give me more memory to work with the data I received.

like image 238
JochenJung Avatar asked Oct 19 '13 08:10

JochenJung


2 Answers

It is interesting that at startup your script is taking so much memory. But I'd suggest you to modify your program in such a way that it can work with lesser amount of memory.

$in = file_get_contents("php://input");

will load all the input data in memory, which is bad. Instead try to read a few KB's of data in memory, process it and the proceed with the rest until you have consumed all the data.

You can use http://php.net/manual/en/function.stream-get-line.php

like image 164
adesh Avatar answered Oct 12 '22 01:10

adesh


Do you have xDebug enabled on your server? It could another extension like that. phpinfo() will tell you what extensions are installed.

What is the memory usage for a simple script like

<?php 
echo memory_get_usage(false) . "\n";
echo memory_get_usage(true) . "\n";
echo "test\n";
?>

Also try

var_dump(get_defined_vars()); 

to see all the variable loaded in your script.

like image 37
Chris Gunawardena Avatar answered Oct 12 '22 02:10

Chris Gunawardena