不要在循环体中使用 array_merge ()-php教程

资源魔 30 0
题目是没有要正在轮回体中应用 array_merge(),其实这只是本篇文章的论断之一

上面咱们一同钻研一下 php 言语中数组的兼并(这里先没有思考递归兼并)

四种兼并数组的形式比照

四种常见的兼并数组的形式比照

写代码

咱们晓得 array_merge() 以及 运算符 + 均可以拼接数组

创立一个类

ArrayMerge()
● eachOne() 轮回体应用 array_merge() 兼并
● eachTwo() 轮回体完结后应用 array_merge() 兼并
● eachThree() 轮回体嵌套完成数组兼并
● eachFour() 轮回体应用 运算符 + 拼接兼并
● getNiceFileSize() 将内存占用转化成人类可读的形式

/**
 * Class ArrayMerge
 */
class ArrayMerge
{
    /**
     * @param int $times
     * @return array
     */
    public static 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;
    }
    /**
     * @param int $times
     * @return array
     */
    public static 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);
    }
    /**
     * @param int $times
     * @return array
     */
    public static function eachThree(int $times): array
    {
        $a = [];
        $b = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
        for ($i = 0; $i < $times; $i++) {
            foreach ($b as $item) {
                $a[] = $item;
            }
        }
        return $a;
    }
    /**
     * @param int $times
     * @return array
     */
    public static function eachFour(int $times): array
    {
        $a = [];
        $b = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
        for ($i = 0; $i < $times; $i++) {
            $a = $b + $a;
        }
        return $a;
    }
    /**
     * 转化内存信息
     * @param      $bytes
     * @param bool $binaryPrefix
     * @return string
     */
    public static function getNiceFileSize(int $bytes, $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);
$a       = ArrayMerge::eachOne(10000);
echo 'count eachOne Result | ' . count($a) . PHP_EOL;
echo 'memory eachOne Result | ' . ArrayMerge::getNiceFileSize(memory_get_usage(true)) . PHP_EOL;
$timeTwo = microtime(true);
$b       = ArrayMerge::eachTwo(10000);
echo 'count eachTwo Result | ' . count($b) . PHP_EOL;
echo 'memory eachTwo Result | ' . ArrayMerge::getNiceFileSize(memory_get_usage(true)) . PHP_EOL;
$timeThree = microtime(true);
$c         = ArrayMerge::eachThree(10000);
echo 'count eachThree Result | ' . count($c) . PHP_EOL;
echo 'memory eachThree Result | ' . ArrayMerge::getNiceFileSize(memory_get_usage(true)) . PHP_EOL;
$timeFour = microtime(true);
$d        = ArrayMerge::eachFour(10000);
echo 'count eachFour Result | ' . count($d) . PHP_EOL;
echo 'memory eachFour Result | ' . ArrayMerge::getNiceFileSize(memory_get_usage(true)) . PHP_EOL;
$timeFive = microtime(true);
echo PHP_EOL;
echo 'eachOne | ' . ($timeTwo - $timeOne) . PHP_EOL;
echo 'eachTwo | ' . ($timeThree - $timeTwo) . PHP_EOL;
echo 'eachThree | ' . ($timeFour - $timeThree) . PHP_EOL;
echo 'eachFour | ' . ($timeFive - $timeFour) . PHP_EOL;
echo PHP_EOL;

后果

count eachOne Result | 100000
memory eachOne Result | 9 MiB
count eachTwo Result | 100000
memory eachTwo Result | 14 MiB
count eachThree Result | 100000
memory eachThree Result | 18 MiB
count eachFour Result | 10           #留意这里
memory eachFour Result | 18 MiB
eachOne | 5.21253490448                 # 轮回体中应用array_merge()最慢,并且消耗内存
eachTwo | 0.0071840286254883            # 轮回体完结后应用array_merge()最快
eachThree | 0.037622928619385           # 轮回体嵌套比轮回体完结后应用array_merge()慢三倍
eachFour | 0.0072360038757324           # 看似也很快,然而兼并的后果有成绩

● 轮回体中应用 array_merge () 最慢,并且消耗内存

● 轮回体完结后应用 array_merge () 最快

● 轮回体嵌套比轮回体完结后应用 array_merge () 慢三倍

● 看似也很快,然而兼并的后果有成绩

兼并数组的坑

咱们留意到刚刚的 eachFour 的后果长度只有 10

上面探索为何会呈现这样的后果

这里拿递归兼并一同做下比照

代码

public static function test(): void
{
    $testA = [
        '111' => 'testA1',
        'abc' => 'testA1',
        '222' => 'testA2',
    ];
    $testB = [
        '111' => 'testB1',
        'abc' => 'testB1',
        '222' => 'testB2',
        'www' => 'testB1',
    ];
    echo 'array_merge($testA, $testB) | ' . PHP_EOL;
    print_r(array_merge($testA, $testB));
    echo '$testA + $testB | ' . PHP_EOL;
    print_r($testA + $testB);
    echo '$testB + $testA | ' . PHP_EOL;
    print_r($testB + $testA);
    echo 'array_merge_recursive($testA, $testB) | ' . PHP_EOL;
    print_r(array_merge_recursive($testA, $testB));
}

后果

+ 号拼接两个数组,后者只会增补前者不的 key,然而会保存数字索引

array_merge() 以及 array_merge_recursive() 会抹去数字索引,一切的数字索引按程序从 0 开端了

array_merge($testA, $testB) |    #数字索引强迫从0开端了 字符key相反的当前者为准
Array
(
    [0] => testA1
    [abc] => testB1
    [1] => testA2
    [2] => testB1
    [3] => testB2
    [www] => testB1
)
$testA + $testB |        #testA失去保存,testB增补了testA中不的key,数字索引失去保存
Array
(
    [111] => testA1
    [abc] => testA1
    [222] => testA2
    [www] => testB1
)
$testB + $testA |        #testB失去保存,testA增补了testB中不的key,数字索引失去保存
Array
(
    [111] => testB1
    [abc] => testB1
    [222] => testB2
    [www] => testB1
)

array_merge_recursive($testA, $testB) | #数字索引从0开端延续了,但数组的程序不被毁坏,相反的字符串 `key` 兼并为一个数组

Array
(
    [0] => testA1
    [abc] => Array
        (
            [0] => testA1
            [1] => testB1
        )
    [1] => testA2
    [2] => testB1
    [3] => testB2
    [www] => testB1
)

剖析

看到这里,你肯定十分纳闷,没想到 array_merge() 另有这样的坑

咱们先来看一看民间的手册

array_merge ( array $array1 [, array $... ] ) : array

array_merge () 将一个或多个数组的单位兼并起来,一个数组中的值附加正在前一个数组的前面。前往作为后果的数组。

假如输出的数组中有相反的字符串键名,则该键名前面的值将笼罩前一个值。但是,假如数组蕴含数字键名,前面的值将没有会笼罩原来的值,而是附加到前面。

假如只给了一个数组而且该数组是数字索引的,则键名会以延续形式从新索引。

只有相反的字符串键名,后边的值才会笼罩后面的值。(然而手册中不诠释为何数字键名的索引被重置了)

那末咱们来看一下源码

PHPAPI int php_array_merge(HashTable *dest, HashTable *src)
{
    zval *src_entry;
    zend_string *string_key;
    if ((dest->u.flags & HASH_FLAG_PACKED) && (src->u.flags & HASH_FLAG_PACKED)) {
        // 天然数组的兼并,HASH_FLAG_PACKED示意数组是天然数组([0,1,2])   参考http://ju.outofmemory.cn/entry/197064
        zend_hash_extend(dest, zend_hash_num_elements(dest) + zend_hash_num_elements(src), 1);
        ZEND_HASH_FILL_PACKED(dest) {
            ZEND_HASH_FOREACH_VAL(src, src_entry) {
                if (UNEXPECTED(Z_ISREF_P(src_entry)) &&
                    UNEXPECTED(Z_REFCOUNT_P(src_entry) == 1)) {
                    ZVAL_UNREF(src_entry);
                }
                Z_TRY_ADDREF_P(src_entry);
                ZEND_HASH_FILL_ADD(src_entry);
            } ZEND_HASH_FOREACH_END();
        } ZEND_HASH_FILL_END();
    } else {
        //遍历猎取key以及vaule
        ZEND_HASH_FOREACH_STR_KEY_VAL(src, string_key, src_entry) {
            if (UNEXPECTED(Z_ISREF_P(src_entry) &&
                Z_REFCOUNT_P(src_entry) == 1)) {
                ZVAL_UNREF(src_entry);
            }
            Z_TRY_ADDREF_P(src_entry);
            //  参考https://github.com/pangudashu/php7-internal/blob/master/7/var.md
            if (string_key) {
                // 字符串key(zend_string)  拔出或许更新元素,会添加key的计数
                zend_hash_update(dest, string_key, src_entry);
            } else {
                //拔出新元素,应用主动的索引值(破案了,索引被重置的缘由正在此)
                zend_hash_next_index_insert_new(dest, src_entry);
            }
        } ZEND_HASH_FOREACH_END();
    }
    return 1;
}

总结

综上所述,兼并数组的没有同形式都存正在肯定的缺点,然而经过咱们下面的探索,咱们理解到

● 轮回体中应用 array_merge() 兼并数组不成取,速率差距达百倍

● array_merge() 兼并数组要慎用,假如注重 key ,且 key 可能为数字,不克不及应用 array_merge() 来兼并,咱们能够采纳轮回体嵌套的形式(留意内层轮回应用 key 进行赋值操作)

● 假如注重 key ,且 key 可能为数字,简略兼并数组能够应用运算符 + ,然而肯定没有要正在轮回体中应用,由于每一次运算的的后果都是天生了一个新的数组

以上就是没有要正在轮回体中应用 array_merge ()的具体内容,更多请存眷资源魔其它相干文章!

标签: php开发教程 php开发资料 php开发自学 array_merge

抱歉,评论功能暂时关闭!