PHP变量引用和内存使用情况

时间:2011-11-03 10:53:34

标签: php variables memory-management reference

根据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. 

我认为:

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

应该消耗更多的内存:

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

因为,如果我理解正确,在第一种情况下我们'重复'值something并将其分配给$y$z最终有3个变量和3个内容,在第二种情况下,我们有3个变量pointing相同的内容。

所以,使用如下代码:

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

我希望内存使用率低于:

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

但两种情况下的内存使用情况都是一样的。

我缺少什么?

2 个答案:

答案 0 :(得分:14)

PHP不会在赋值时复制,但在写入时。有关它的科学讨论,请参见Copy-on-Write in the PHP Language (Jan 18 2009; by Akihiko Tozawa, Michiaki Tatsubori, Tamiya Onodera and Yasuhiko Minamide; PDF file)Do not use PHP references (Jan 10, 2010; by Jan Schlüter)以获得一些乐趣,我自己采取References to the Max以及更多参考资料。

答案 1 :(得分:3)

PHP使用copy-on-write因此在修改它们之前不会为重复的字符串使用更多的内存。