A
A
Alexey Dabalaev2016-06-19 21:30:00
PHP
Alexey Dabalaev, 2016-06-19 21:30:00

How to find out the size (number of bytes occupied) of an object in PHP?

Hello.
C++ has a function sizeof(); to determine the size of an object.
Is there anything similar in PHP for determining the size of an object?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey, 2016-06-19
Protko @Fesor

Is there anything similar in PHP for determining the size of an object?

No, because it doesn't make sense. For the real size of the structures is very difficult to calculate. For example, all string literals (variable names, for example) for 10 instances of objects of the same type will be replaced with pointers to the buffer , and the total size is not so easy to calculate.
The option with memory_get_usage as suggested above will also not work due to the fact that everything is much more complicated inside the interpreter. For example:
class Foo {
    private $bar;
    public function __construct(string $bar) {
       $this->bar = $bar;
    }
}

$start = memory_get_usage();
$a = new Foo('test1');
$middle = memory_get_usage();
$b = new Foo('longer value');
$end = memory_get_usage();

echo $middle - $start, PHP_EOL; // 56
echo $end - $middle, PHP_EOL;  // 56

Actually, it is logical that since we have different sizes of values, then the size of intans should be different. We also do not forget that between the fence of memory consumption, we also have the overhead for a reference to an object + a variable. Also, do not forget that php allocates memory in blocks ....
in a word - PHP does not provide the ability to accurately calculate the size of an instance in memory.

A
Anton Natarov, 2016-06-19
@HanDroid

$before=0;
$a='испытуемая переменная либо массив или объект';
$before = memory_get_usage();
unset($a);
echo 'размер переменной составил: ',$before-memory_get_usage(),' байт';

A
atis //, 2016-06-19
@atis2345

class MyBigClass
{
    var $allocatedSize;
    var $allMyOtherStuff;
}

function AllocateMyBigClass()
{
    $before = memory_get_usage();
    $ret = new MyBigClass;
    $after = memory_get_usage();
    $ret->allocatedSize = ($after - $before);

    return $ret;
}

stackoverflow.com/questions/1351855/getting-size-i...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question