標題是不要在循環體中使用 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 $... ] ) : arrayarray_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 可能為數字,簡單合併數組可以使用運算符 + ,但是一定不要在循環體中使用,因為每次運算的的結果都是生成了一個新的數組。
-END-
▼請點擊下方:「閱讀原文」,在線查看全部文章內容!