2

In case I have 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:

6
  • Check it out for yourself. See get_memory_usage() Commented Jul 28, 2011 at 17:44
  • @JohnCartwright: Wow. It looks it's not copying themselves. Look first, second Commented Jul 28, 2011 at 17:48
  • @genesis: You need to write another get_memory_usage() for the first variable, array or object. Your code doesn't do anything. Commented Jul 28, 2011 at 17:53
  • Oops, I meant memory_get_usage() Commented Jul 28, 2011 at 17:54
  • @Jitamaro: see my question edited. It is testing exact code I have in question Commented Jul 28, 2011 at 17:57

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

8 Comments

How is it possible that it takes a lot more memory for me? extensions?
is there an option to kill this smart behaviour? I can compile myself!
@genesis: edited the classes answer in. And why it takes more? There's a random factor of course, but this is from a lean & mean command-line php script, not in a webserver, which is quite a difference.
@Jitamaro: the C source code of PHP is available, go ahead. I can't for the life of me think why you would destroy this behavior though. There are as of yet no ill sideeffects of this behavior that I know of.
@genesis: you see you need 3 memory_get_usage!!! I want an upvote now for my post or I delete it!!!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.