根据 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 个变量指向
相同的内容。
因此,使用如下代码:
$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);
但是两种情况下的内存使用是相同的。
我错过了什么?
最佳答案
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有更多引用资料。
关于PHP变量引用和内存使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7993658/