Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this php function leak memory

Tags:

php

php-5.3

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

like image 827
Joris Mans Avatar asked Feb 27 '26 23:02

Joris Mans


1 Answers

Because you're creating a new function every time that function runs.

Since you're using 5.3, you can replace create_function with an anonymous function and see if that helps:

    static private function from_camel_case($str)
    {
        $str[0] = strtolower($str[0]);
        $result = preg_replace_callback('/([A-Z])/', function($matches) {
          return '_' . strtolower($matches[1]);
        }, $str);
        return $result;
    }

Or extract the callback into a normal function:

    static private function from_camel_case($str)
    {
        $str[0] = strtolower($str[0]);
        $result = preg_replace_callback('/([A-Z])/', array(__CLASS__, 'replace_case'), $str);
        return $result;
    }

    static private function replace_case($matches) {
      return '_' . strtolower($matches[1]);
    }