Wednesday, October 20, 2010

Memory Leak Caused By Variable and String Concatenation On Long Running PHP Applications

This memory leak is observed if the following conditions are met:

1. A variable is being concatenated.
2. The data length buffered within the variable is more than 8-bytes, 4-bytes on class (not sure why).
3. Using double quotes to evaluate the variable(s) automatically.
4. Present on PHP 5.1.x below

Take the following example:

Has memory leak:

<?php
while(true) {
$app = "I am causing a memory leak \n";
echo "Shit, $app";
echo memory_get_usage();
sleep(1);
}

Doesn't have a memory and lower initial memory usage.

<?php
while(true) {
$app = "I am causing a memory leak \n";
echo 'Shit, ' . $app;
echo memory_get_usage();
sleep(1);
}
Note: both code must be run on CLI version of PHP to observed this memory leak properly. Memory leak should not be present on WEB APPLICATIONS since a new process is spawned everytime and automatic garbage collection happens every after request. On a longer term, I am recommending upgrade to a higher version of PHP. At the time of this writing the, PHP's stable version is PHP 5.3.3 - http://php.net.
  • Related Links Widget for Blogspot

No comments: