12

According to php manual:

<?php
$a =& $b;
?>
// Note:
// $a and $b are completely equal here. $a is not pointing to $b or vice versa.
// $a and $b are pointing to the same place. 

I assume that:

<?php
$x = "something";
$y = $x;
$z = $x;

should consume more memory than:

<?php
$x = "something";
$y =& $x;
$z =& $x;

because, if i understood it right, in the first case we 'duplicate' the value something and assign it to $y and $z having in the end 3 variables and 3 contents, while in the second case we have 3 variables pointing the same content.

So, with a code like:

$value = "put something here, like a long lorem ipsum";
for($i = 0; $i < 100000; $i++)
{
    ${"a$i"} =& $value;
}
echo memory_get_usage(true);

I expect to have a memory usage lower than:

$value = "put something here, like a long lorem ipsum";
for($i = 0; $i < 100000; $i++)
{
    ${"a$i"} = $value;
}
echo memory_get_usage(true);

But the memory usage is the same in both cases.

What am I missing?

2 Answers 2

14

PHP does not duplicate on assignment, but on write. See Copy-on-Write in the PHP Language (Jan 18 2009; by Akihiko Tozawa, Michiaki Tatsubori, Tamiya Onodera and Yasuhiko Minamide; PDF file) for a scientific discussion of it, Do not use PHP references (Jan 10, 2010; by Jan Schlüter) for some fun and my own take is References to the Max with more references.

0
4

PHP uses copy-on-write so it won't use more memory for the duplicated strings until you modify them.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.