为什么这个简单的php脚本会泄漏内存?
希望避免将来在php程序(drupal模块等)中发生内存泄漏我一直在搞砸泄漏内存的简单php脚本。
php专家可以帮助我找到这个脚本导致内存使用量不断攀升的原因吗?
尝试自己运行它,更改各种参数。结果很有趣。在这里:
<?php
function memstat() {
print "current memory usage: ". memory_get_usage() . "\n";
}
function waste_lots_of_memory($iters) {
$i = 0;
$object = new StdClass;
for (;$i < $iters; $i++) {
$object->{"member_" . $i} = array("blah blah blha" => 12345);
$object->{"membersonly_" . $i} = new StdClass;
$object->{"onlymember"} = array("blah blah blha" => 12345);
}
unset($object);
}
function waste_a_little_less_memory($iters) {
$i = 0;
$object = new StdClass;
for (;$i < $iters; $i++) {
$object->{"member_" . $i} = array("blah blah blha" => 12345);
$object->{"membersonly_" . $i} = new StdClass;
$object->{"onlymember"} = array("blah blah blha" => 12345);
unset($object->{"membersonly_". $i});
unset($object->{"member_" . $i});
unset($object->{"onlymember"});
}
unset($object);
}
memstat();
waste_a_little_less_memory(1000000);
memstat();
waste_lots_of_memory(10000);
memstat();
对我来说,输出是:
current memory usage: 73308
current memory usage: 74996
current memory usage: 506676
[已编辑以取消设置更多对象成员]