【问题标题】:PHP variables reference and memory usagePHP 变量引用和内存使用
【发布时间】:2011-12-21 01:47:44
【问题描述】:

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);

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

我错过了什么?

【问题讨论】:

    标签: php variables memory-management reference


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      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 以及更多参考资料。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-15
        • 1970-01-01
        相关资源
        最近更新 更多