5

据我了解,当我按值传递数组时,会创建数组的副本。即在下面的程序中$y & $z 应该需要与$x 相同的内存。但是内存利用率几乎没有增加。很明显我的理解是错误的,任何人都可以解释原因。

for($i=0;$i<1000000;$i++)

        $x[] = $i; // memory usage : 76519792


echo memory_get_usage(); 

function abc($y){

    $y[1] = 1; //memory usage  : 76519948 
    $z[]= $y;   //memory usage : 76520308

}
4

1 回答 1

3

我听说php使用copy-on-write: http ://en.wikipedia.org/wiki/Copy-on-write

举个例子:

<?
for($i=0;$i<100000;$i++)
    $x[] = $i;

// we output the memory use:
echo memory_get_usage().'<br/>';  // outputs 14521040

// here we equate $y to $x, but instead of creating a copy, 
// php engine just creates a pointer to the same memory space
$y = $x;

echo memory_get_usage().'<br/>';  // outputs 14521128

// here we change something in y, now php engine 
// "creates a seperate copy" for y and makes the change
$y[1]=8;

echo memory_get_usage().'<br/>';  // outputs 23569904

?>

以及函数调用的类似行为:

<?
for($i=0;$i<100000;$i++)
    $x[] = $i;

echo memory_get_usage().'<br/>'; /* 14524968 */

function abc($y){
    echo memory_get_usage().'<br/>'; /* 14524968 */
    $y[1] = 1;
    echo memory_get_usage().'<br/>'; /* 23573752 */
    $z[]= $y;  
    echo memory_get_usage().'<br/>'; /* 23574040 */

}
abc($x);
echo memory_get_usage().'<br/>'; /* 14524968 */
?>

PS:我在windows上测试这个,可能在linux上不一样

于 2012-08-16T13:11:36.977 回答