Jump to content

Size of php var in memory


The Letter E

Recommended Posts

Hey everybody,

 

Is there a way to see how much memory a php var takes up.

 

example

$var = array('val1', 'val2', 'val3', 'val4');
$size = mem($var);

 

Basically i'm creating custom debug logs for  all memcached objects and want to report bytesize of each payload.

 

Thanks in advance,

 

E

Link to comment
https://forums.phpfreaks.com/topic/242568-size-of-php-var-in-memory/
Share on other sites

Yes using memory_get_usage() http://fi2.php.net/manual/en/function.memory-get-usage.php . Example:

 

class A
{
    public $var = array();

    public function __construct()
    {
        for ($i=0;$i<10;$i++) {
            $this->var[] = new B();
        }
    }
}


class B
{
    public $varb = array();

    public function __construct()
    {
        for ($i=0;$i<10000;$i++) {
            $this->var[] = rand();
        }
    }
}

echo "Just after load ".intval(memory_get_usage()/(1024*1024))."MB \n";
$a = new A();
echo "After creating A() ".intval(memory_get_usage()/(1024*1024))."MB \n";
unset($a);
echo "After destroying A() ".intval(memory_get_usage()/(1024*1024))."MB \n";

Hey TeNDoLLA,

 

unfortunately to get the info i need using memory_get_usage I would have to run it in my view and run it once before I render a chached object and once after then substract the values to get the size of that one cached instance...which is not ideal. I am looking for something I can run in my controller and apply directly to a certain payload and return its bytesize.

 

Thanks for the response.

 

E

It's not 100% precise, and it's liable to change over PHP versions. Given I = PHP_INT_SIZE, for PHP 5.3 it's something like this:

- (General overhead: 3I + 2)

- Strings: string length + 1

- Numbers: 0

- Arrays: 10I + 3 + number of items * (9I + 1 + item size + (an unknown amount))

- Objects: I + size of properties + (number of non-magic functions + 25) * I + (an unknown amount)

 

About unknown amounts: I don't know and I can't take the time now to find more information.

About objects: the above doesn't take functions into account very well. Takes more to figure out than just looking at the PHP source code.

 

If you care about getting very precise numbers you should write a PHP extension, in which you'll have direct access to the structs and variables and memory used.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.