开发者

Does PHP take RAM when defining variable from variable and taking instance of object to another variable?

In case I hav开发者_如何学Ce this code

<?php
$array = array();
for ($i=1;$i<100000;$i++){
    $array[$i] = md5(rand(0,9999999999999999));
}

$array2 = $array;

$array takes about 0.5MB RAM, let's say. Does PHP proccess take about 1.0MB RAM with $array2 = $array; ? and in this case

<?php
class rand{
    public $array;
    function rand(){
        $this->array = array();
        for ($i=1;$i<100000;$i++){
            $this->array[$i] = md5(rand(0,9999999999999999));
        }

    }
}

$class = new rand();
$class2 = $class;

$class takes about 0.5MB RAM, let's say . Does PHP proccess take 1.0MB with $class2 = $class?

is it same?

Tests:

  • First
  • Second


This is what the PHP manual in the reference section warns about: the Engine is smart enough. Setting the $array2 = $array; does not cause duplicate storage, as PHP recognizes they are still both the same. However, try a $array[2] = 'something;' after that. PHP detects the difference, and only then will copy the values.

<?php
$array = array();
for ($i=1;$i<100000;$i++){
    $array[$i] = md5(rand(0,9999999999999999));
}
echo memory_get_usage().PHP_EOL;
$array2 = $array;
echo memory_get_usage().PHP_EOL;
$array['foo'] = 'bar';
echo memory_get_usage().PHP_EOL;
//17252052
//17252156
//23776652

Classes are references by default, and only a clone $object would result in 2 objects in PHP >= 5.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜