tags:

views:

249

answers:

3

I am curious how PHP handles variables in memory? If I have 100 constants or variables set that hold values related to my application and not on a per user basis, like site name, version number, things like that, which all users have the same value. Will PHP put these 100 variables into ram 100 times if 100 users are hitting the page at the same time? Or does it somehow only store the value in RAM 1 time and all users feed off of that? Sorry if this is not clear, I will try to re-phrase it if it is not clear enough, thanks.

+1  A: 

You could experiment with memory_get_usage() to monitor how memory is being handled in response to certain declarations. For instance, I worked up the following:

echo memory_get_usage(); // 84944
$var = "foo";
echo memory_get_usage(); // 85072
unset($var);
echo memory_get_usage(); // 85096

Comparing to storing in $_SESSION:

echo memory_get_usage(); // 85416
$_SESSION['var'] = "foo";
echo memory_get_usage(); // 85568
unset($_SESSION['var']);
echo memory_get_usage(); // 85584
Jonathan Sampson
+2  A: 

If the variable just a $variable, then yes, the 100 variables will be multiplied by 100 users. Even when we're counting session storage, during the time the request is running, these variables are also stored in memory, in $_SESSION.

However, I doubt you really need to be concerned, the amount of space taken up by a few variables is rarely an issue; many large PHP applications will load thousands of variables for each request, and then clean them out at the end of the request. The PHP footprint is not terribly large, and memory control is more up to your deployment method of PHP (mod_php vs CGI/FastCGI) than anything to do with any applications you run.

To be more specific, whether your machine can handle 100 simultaneous requests is mostly unrelated to your PHP script, as the PHP interpreter generally takes up a lot more memory than the scripts it runs. If, however, each of those scripts is loading a very large file into a string (or a large database result set, or the like) then it is possible that your script's memory use is a concern. For the general case however, it's something that comes down to the webserver's setup.

Crast
+1  A: 

Only code pages are implicitly shared between processes. Data is separate for processes and combined for threads unless this is explicitly overridden via e.g. SysV shared memory.

Ignacio Vazquez-Abrams