PHP如何为变量分配和释放内存?

时间:2011-05-11 21:56:31

标签: php memory variables memory-management php-internals

我想知道PHP何时释放用于变量的内存

例如

function foo(){
  $foo = 'data';
  return $foo;  // <- is the memory space for `$foo` emptied at this point?
}

比它慢:

function foo(){
  return 'data'; 
}

1 个答案:

答案 0 :(得分:9)

好吧,让我们找出来!

<?php
$checkpoints = array( 'start' => memory_get_usage() );

$checkpoints['before defining demo1'] = memory_get_usage();
function demo1() { $foo = 'data'; return $foo; }
$checkpoints['after defining demo1'] = memory_get_usage();

$checkpoints['before defining demo2'] = memory_get_usage();
function demo2() { return 'data'; }
$checkpoints['after defining demo2'] = memory_get_usage();


$checkpoints['before calling demo1'] = memory_get_usage();
demo1();
$checkpoints['after calling demo1'] = memory_get_usage();

$checkpoints['before calling demo2'] = memory_get_usage();
demo2();
$checkpoints['after calling demo2'] = memory_get_usage();

$checkpoints['before calling demo1 with storage'] = memory_get_usage();
$storage1 = demo1();
$checkpoints['after calling demo1 with storage'] = memory_get_usage();

$checkpoints['before calling demo2 with storage'] = memory_get_usage();
$storage2 = demo2();
$checkpoints['after calling demo2 with storage'] = memory_get_usage();

echo '<pre>';
print_r($checkpoints);

$last_key = 'start';
foreach($checkpoints as $key => $value) {
    echo "{$key} - {$last_key} = ", ($value - $checkpoints[$last_key]), "\n";
    $last_key = $key;
}

在PHP 5.3.6下,我的输出是:

Array
(
    [start] => 321920
    [before defining demo1] => 322188
    [after defining demo1] => 322788
    [before defining demo2] => 322880
    [after defining demo2] => 323188
    [before calling demo1] => 323280
    [after calling demo1] => 323368
    [before calling demo2] => 323464
    [after calling demo2] => 323552
    [before calling demo1 with storage] => 323692
    [after calling demo1 with storage] => 323896
    [before calling demo2 with storage] => 324000
    [after calling demo2 with storage] => 324204
)

然后

start - start = 0
before defining demo1 - start = 268
after defining demo1 - before defining demo1 = 600
before defining demo2 - after defining demo1 = 92
after defining demo2 - before defining demo2 = 308
before calling demo1 - after defining demo2 = 92
after calling demo1 - before calling demo1 = 88
before calling demo2 - after calling demo1 = 96
after calling demo2 - before calling demo2 = 88
before calling demo1 with storage - after calling demo2 = 140
after calling demo1 with storage - before calling demo1 with storage = 204
before calling demo2 with storage - after calling demo1 with storage = 104
after calling demo2 with storage - before calling demo2 with storage = 204

在初始调用demo1demo2期间,丢弃输出的内存增加很可能是由于创建了用于存储内存使用的变量。

但是,这里的底线是两个存储示例,其中两个存储示例都直接返回数据并在返回它之前将其分配给变量导致给定数据的确切内存使用

结论:PHP在这个简单的测试中看起来足够聪明,不会不必要地复制字符串变量 - 尽管要注意两个函数之间的内存使用差异。只是声明demo1函数需要更多的内存来声明demo2。几百个字节,真的。