I have a long running operation in PHP and it always crashed with an out of memory.
So i started logging mem usage with:
$result = memory_get_usage() / 1024;
echo $result;
By commenting parts of the code I found the “guilty” one, responsible for eating up all my ram.
This is the code:
static private function from_camel_case($str)
{
$str[0] = strtolower($str[0]);
$func = create_function('$c', 'return "_" . strtolower($c[1]);');
$result = preg_replace_callback('/([A-Z])/', $func, $str);
return $result;
}
It basically converts text in camelcase to lowercase with underscores.
Why is this leaking?
I am running PHP 5.3.5 in MAMP on my Mac OS X Lion
You are creating a function using
create_functionevery time you call it. Functions in PHP are always global, which means it will exist till the end of the script. That’s why every time you call it, it will allocate some memory and never deallocate it.You should create the function only once, or I’s sure you can rewrite the whole thing using callbacks to get rid of the memory leak.