gpt4 book ai didi

php - 在 PHP 中管理大型数组

转载 作者:行者123 更新时间:2023-12-01 02:28:01 24 4
gpt4 key购买 nike

我正在为某人挖掘数百万个旧日志条目的数据,并且真的想在这件事上使用 PHP 来呈现 Material ,并将它们轻松链接到现有的 PHP 系统。

我在终端 (OSX 10.8) 的 PHP 5.4.4 中运行此代码:

// Settings
ini_set('error_reporting', E_ALL); // Shows all feedback from the parser for debugging
ini_set('max_execution_time', 0); // Changes the 30 seconds parser exit to infinite
ini_set('memory_limit', '512M'); // Sets the memory that may be used to 512MegaBytes


echo 'Start memory usage: '.(memory_get_usage(TRUE) / 1024)."\n";

$x = Array();
for ($i = 0; $i < 1e7; $i++) {
$x[$i] = 1 * rand(0, 10);
//unset($x[$i]);
}

echo 'End memory usage: '.(memory_get_usage(TRUE) / 1024)."\n";
echo 'Peak memory usage: '.(memory_get_peak_usage(TRUE) / 1024)."\n";

这是一千万次循环的简单测试。与在 Python 中使用字典相比,泄漏真的很糟糕:(。

当我取消引用 unset() 函数来测试用法时,它立即变成了 unicorn 和彩虹。所以强制释放内存似乎很顺利。

有什么方法可以在 512M 内存限制内保持 10-5000 万个数组条目?

我无法想象我什么时候会用这些循环做一些正则表达式..

最佳答案

使用 SplFixedArray因为你真的需要看How big are PHP arrays (and values) really? (Hint: BIG!)

$t = 1e6;
$x = array();
for($i = 0; $i < $t; $i ++) {
$x[$i] = 1 * rand(0, 10);
}

输出
Start memory usage: 256
End memory usage: 82688
Peak memory usage: 82688


$t = 1e6;
$x = new SplFixedArray($t);
for($i = 0; $i < $t; $i ++) {
$x[$i] = 1 * rand(0, 10);
}

输出
Start memory usage: 256
End memory usage: 35584
Peak memory usage: 35584

但更好的是我认为你应该考虑一个基于内存的数据库,比如 REDIS

关于php - 在 PHP 中管理大型数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14880830/

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