首頁  >  文章  >  後端開發  >  不要在循環體中使用 array_merge ()

不要在循環體中使用 array_merge ()

藏色散人
藏色散人轉載
2019-10-30 14:02:372698瀏覽

標題是不要在循環體中使用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(&#39;B&#39;, &#39;KiB&#39;, &#39;MiB&#39;, &#39;GiB&#39;, &#39;TiB&#39;, &#39;PiB&#39;);
            if ($bytes === 0) {
                return &#39;0 &#39; . $unit[0];
            }
            return @round($bytes / (1024 ** ($i = floor(log($bytes, 1024)))),
                    2) . &#39; &#39; . ($unit[(int)$i] ?? &#39;B&#39;);
        }
        $unit = array(&#39;B&#39;, &#39;KB&#39;, &#39;MB&#39;, &#39;GB&#39;, &#39;TB&#39;, &#39;PB&#39;);
        if ($bytes === 0) {
            return &#39;0 &#39; . $unit[0];
        }
        return @round($bytes / (1000 ** ($i = floor(log($bytes, 1000)))),
                2) . &#39; &#39; . ($unit[(int)$i] ?? &#39;B&#39;);
    }
}

使用

先分配多點記憶體

輸出記憶體佔用,合併後的陣列長度,並記錄每一步的用時

ini_set(&#39;memory_limit&#39;, &#39;4000M&#39;);
$timeOne = microtime(true);
$a       = ArrayMerge::eachOne(10000);
echo &#39;count eachOne Result | &#39; . count($a) . PHP_EOL;
echo &#39;memory eachOne Result | &#39; . ArrayMerge::getNiceFileSize(memory_get_usage(true)) . PHP_EOL;
$timeTwo = microtime(true);
$b       = ArrayMerge::eachTwo(10000);
echo &#39;count eachTwo Result | &#39; . count($b) . PHP_EOL;
echo &#39;memory eachTwo Result | &#39; . ArrayMerge::getNiceFileSize(memory_get_usage(true)) . PHP_EOL;
$timeThree = microtime(true);
$c         = ArrayMerge::eachThree(10000);
echo &#39;count eachThree Result | &#39; . count($c) . PHP_EOL;
echo &#39;memory eachThree Result | &#39; . ArrayMerge::getNiceFileSize(memory_get_usage(true)) . PHP_EOL;
$timeFour = microtime(true);
$d        = ArrayMerge::eachFour(10000);
echo &#39;count eachFour Result | &#39; . count($d) . PHP_EOL;
echo &#39;memory eachFour Result | &#39; . ArrayMerge::getNiceFileSize(memory_get_usage(true)) . PHP_EOL;
$timeFive = microtime(true);
echo PHP_EOL;
echo &#39;eachOne | &#39; . ($timeTwo - $timeOne) . PHP_EOL;
echo &#39;eachTwo | &#39; . ($timeThree - $timeTwo) . PHP_EOL;
echo &#39;eachThree | &#39; . ($timeFour - $timeThree) . PHP_EOL;
echo &#39;eachFour | &#39; . ($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 = [
        &#39;111&#39; => &#39;testA1&#39;,
        &#39;abc&#39; => &#39;testA1&#39;,
        &#39;222&#39; => &#39;testA2&#39;,
    ];
    $testB = [
        &#39;111&#39; => &#39;testB1&#39;,
        &#39;abc&#39; => &#39;testB1&#39;,
        &#39;222&#39; => &#39;testB2&#39;,
        &#39;www&#39; => &#39;testB1&#39;,
    ];
    echo &#39;array_merge($testA, $testB) | &#39; . PHP_EOL;
    print_r(array_merge($testA, $testB));
    echo &#39;$testA + $testB | &#39; . PHP_EOL;
    print_r($testA + $testB);
    echo &#39;$testB + $testA | &#39; . PHP_EOL;
    print_r($testB + $testA);
    echo &#39;array_merge_recursive($testA, $testB) | &#39; . 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中文網其他相關文章!

陳述:
本文轉載於:learnku.com。如有侵權,請聯絡admin@php.cn刪除