Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP variables reference and memory usage

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?

like image 734
Strae Avatar asked Nov 03 '11 10:11

Strae


2 Answers

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

like image 188
Benjie Avatar answered Sep 25 '22 22:09

Benjie


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.

like image 32
hakre Avatar answered Sep 23 '22 22:09

hakre