PHP系列 | 不要在循环体中使用 array_merge()
直接上代码
/**
* @desc: 将内存占用转化成人类可读的方式
* @param int $bytes
* @param bool $binaryPrefix
* @return string|null
* @author Tinywan(ShaoBo Wan)
*/
function getNiceFileSize(int $bytes, bool $binaryPrefix = true): ?string
{
if ($binaryPrefix) {
$unit = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB');
if ($bytes === 0) {
return '0 ' . $unit[0];
}
return @round($bytes / (1024 ** ($i = floor(log($bytes, 1024)))),
2) . ' ' . ($unit[(int)$i] ?? 'B');
}
$unit = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
if ($bytes === 0) {
return '0 ' . $unit[0];
}
return @round($bytes / (1000 ** ($i = floor(log($bytes, 1000)))),
2) . ' ' . ($unit[(int)$i] ?? 'B');
}
ini_set('memory_limit', '4000M');
$timeOne = microtime(true);
// (1)循环中使用array_merge
function eachOne(int $times): array
{
$a = [];
$b = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for ($i = 0; $i < $times; $i++) {
$a = array_merge($a, $b);
}
return $a;
}
$a = eachOne(20000);
$timeTwo = microtime(true);
echo ' [x] eachOne Count Result : ' . count($a) . PHP_EOL;
echo ' [x] eachOne Memory Result : ' . getNiceFileSize(memory_get_usage(true)) . PHP_EOL;
echo ' [x] eachOne Time Result : ' . ($timeTwo - $timeOne) . PHP_EOL;
echo ' [x] ----------------完美分隔符-------------- '. PHP_EOL;
// (2)循环后使用array_merg合并
function eachTwo(int $times): array
{
$a = [[]];
$b = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for ($i = 0; $i < $times; $i++) {
$a[] = $b;
}
return array_merge(...$a);
}
$aa = eachTwo(20000);
$timeThree = microtime(true);
echo ' [x] eachTwo Count Result : ' . count($aa) . PHP_EOL;
echo ' [x] eachTwo Memory Result : ' . getNiceFileSize(memory_get_usage(true)) . PHP_EOL;
echo ' [x] eachTwo Time Result : ' . ($timeThree - $timeTwo) . PHP_EOL;
测试结果
[x] eachOne Count Result : 200000
[x] eachOne Memory Result : 12 MiB
[x] eachOne Time Result : 14.734979152679
[x] ----------------完美分隔符--------------
[x] eachTwo Count Result : 200000
[x] eachTwo Memory Result : 22 MiB
[x] eachTwo Time Result : 0.0043318271636963
http://www.web3.xin/index/article/396.html
标签:
php7
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构