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?

hakre
  • 193,403
  • 52
  • 435
  • 836
Strae
  • 18,807
  • 29
  • 92
  • 131

2 Answers2

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.

hakre
  • 193,403
  • 52
  • 435
  • 836
4

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

Benjie
  • 7,701
  • 5
  • 29
  • 44