据我所知,当我按值传递数组时,会创建一个数组副本.即在下面的程序中,$ 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
}
Run Code Online (Sandbox Code Playgroud)
我听说 php 使用写时复制: 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
?>
Run Code Online (Sandbox Code Playgroud)
以及与函数调用类似的行为:
<?
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 */
?>
Run Code Online (Sandbox Code Playgroud)
PS:我是在windows上测试的,linux上可能不一样
| 归档时间: |
|
| 查看次数: |
123 次 |
| 最近记录: |