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

posted @ 2022-04-08 14:35  Tinywan  阅读(46)  评论(0编辑  收藏  举报