gpt4 book ai didi

php - json_decode 和内存清除

转载 作者:可可西里 更新时间:2023-11-01 13:31:26 25 4
gpt4 key购买 nike

我有一个大型 JSON 文件列表(最小文件是 500 Ko,最大文件是 100 Mo)。

我需要独立处理每个文件。我的问题是每个文件后内存使用量越来越多,即使我清除了所有内存也是如此。

例子:

foreach ($files as $file) {
json_decode(file_get_contents($file->getRealpath()), true);

$memory = memory_get_usage(true);
echo 'Memory: '.@round($memory / pow(1024,($i=floor(log($memory, 1024)))), 2).' '.['b', 'kb', 'mb', 'gb', 'tb', 'pb'][$i]."\n";

gc_collect_cycles();
}

结果:

Memory: 6 mb
(...)
Memory: 6 mb
Memory: 6 mb
Memory: 10 mb
Memory: 10 mb
Memory: 10 mb
(...)
Memory: 12 mb
Memory: 12 mb
Memory: 12 mb
(...)
Memory: 490 mb
Memory: 490 mb
Memory: 490 mb
(...)
Memory: 946 mb
Memory: 944 mb
Memory: 944 mb
(...)

内存越来越大,直到 PHP 告诉我他不能再增加了。如您所见,在这个示例中我除了 json_decode() 之外什么也没做,没有分配变量或其他任何东西。那么为什么我的内存会长成这样,我该如何清除它呢?

最佳答案

检查您尝试获取内容的文件的大小。这可能会更大,因此会占用内存

或者

您需要检查哪个变量占用过多内存,您可以使用 strlen() 它不会为您提供 var 占用的确切内存,但 length 有助于找到近似值。

并且您应该取消设置未使用的变量以清除内存。

unset($decoded_data);

或设置

$var = null

当您使用 unset 时,内存只会在垃圾收集器决定时被释放,但是当您将变量设置为不同的值(在本例中为 null)时,您当然可能会释放一些内存,但代价是的 CPU。

我会推荐你​​使用

https://github.com/salsify/jsonstreamingparser

This is a simple, streaming parser for processing large JSON documents. Use it for parsing very large JSON documents to avoid loading the entire thing into memory, which is how just about every other JSON parser for PHP works.

关于php - json_decode 和内存清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47155877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com