简体   繁体   English

为什么PHP脚本会不断占用更多内存?

[英]Why does a PHP script constantly take up more memory?

See this example: 看这个例子:

echo memory_get_usage() . "\n"; // 36640
$a = str_repeat("Hello", 4242);
echo memory_get_usage() . "\n"; // 57960
unset($a);
echo memory_get_usage() . "\n"; // 36744

Can anyone explain why after un-setting the variable the memory usage does not return to 36640 任何人都可以解释为什么在取消设置变量后,内存使用量不会返回到36640

If you do it twice the memory will stay at 36744... 如果你这样做两次,内存将保持在36744 ......

echo memory_get_usage() . "\n"; // 36640
$a = str_repeat("Hello", 4242);
echo memory_get_usage() . "\n"; // 57960
unset($a);
echo memory_get_usage() . "\n"; // 36744
$a = str_repeat("Hello", 4242);
unset($a);
echo memory_get_usage() . "\n"; // -> 36744

Garbage collection is an expensive operation, even if there's only a single variable to unset. 即使只有一个变量未设置,垃圾收集也是一项昂贵的操作。 PHP won't run the collector each time you unset a var, as that'd waste a huge amount of CPU time. 每次取消设置var时,PHP都不会运行收集器,因为这会浪费大量的CPU时间。

PHP will only run the collector when it has to, as in when something wants more memory than is available. PHP只会在必要时运行收集器,就像需要更多内存的时候一样。

What is your PHP version? 你的PHP版本是什么? The garbage collector in versions less than 5.3 is not really good. 小于5.3版本的垃圾收集器并不是很好。 Please read this link to understand why: 请阅读此链接以了解原因:

Garbage collector 垃圾收集器

Just posting this. 只是张贴这个。

I just ran it as a test for fun on PHP 5.3, the results are pretty clear to what powtac said: 我只是把它作为PHP 5.3上的测试来运行,结果很清楚powtac说的是什么:

630744
652280
630808
630808
652280
630808
630808
652280
630808
630808
652280
630808
630808
652280
630808
630808
652280
630808

So yea, after the initial unset it appears to be consistent throughout. 所以,在最初的未unset之后,它似乎始终如一。 Code tested with: 代码测试:

while (1) {
        echo memory_get_usage() . "\n"; // 36640
        $a = str_repeat("Hello", 4242);
        echo memory_get_usage() . "\n"; // 57960
        unset($a);
        echo memory_get_usage() . "\n"; // 36744
}

Caution: that is an infinite loop :) 警告:这是一个无限循环:)

I'll try to give one possible explanation, but I cannot claim that it is the right one. 我会尝试给出一个可能的解释,但我不能说它是正确的。

PHP stores variables in a hash table (because of it's dynamic nature). PHP将变量存储在哈希表中(因为它具有动态特性)。 This hash table consists of "buckets" (linked lists of elements). 该哈希表由“桶”(链接的元素列表)组成。 As the number of elements grows the number of buckets is increased, too (to be precise: The number of buckets is doubled as soon as the limit is reached). 随着元素数量的增加,桶的数量也会增加(确切地说:一旦达到限制,桶的数量就会增加一倍)。

Thus it could be the case, that the creation of your variable results in an increase of buckets. 因此可能就是这样,变量的创建导致了桶的增加。 As these buckets aren't removed again, the memory usage stays. 由于这些存储桶不会再次移除,因此内存使用率会保持不变。

But again: Only guessing. 但又一次:只是在猜测。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM