我想指出的是,雖然其他評論指出展開運算符應該比 `array_merge` 更快,但我實際上發現對於一般陣列來說情況恰恰相反。在 PHP 7.4 和 PHP 8.0 中都是如此。對於大多數應用程式來說,差異應該可以忽略不計,但我還是想指出這一點,以確保準確性。
以下是測試用的程式碼以及結果
<?php
$before = microtime(true);
for ($i=0 ; $i<10000000 ; $i++) {
$array1 = ['apple','orange','banana'];
$array2 = ['carrot','lettuce','broccoli'];
$array1 = [...$array1,...$array2];
}
$after = microtime(true);
echo ($after-$before) . " sec for spread\n";
$before = microtime(true);
for ($i=0 ; $i<10000000 ; $i++) {
$array1 = ['apple','orange','banana'];
$array2 = ['carrot','lettuce','broccoli'];
$array1 = array_merge($array1,$array2);
}
$after = microtime(true);
echo ($after-$before) . " sec for array_merge\n";
?>
PHP 7.4
1.2135608196259 秒,使用展開運算符
1.1402177810669 秒,使用 array_merge
PHP 8.0
1.1952061653137 秒,使用展開運算符
1.099925994873 秒,使用 array_merge