循环里面使用 array 相关函数会导致运行慢,且占用CPU

例如:

$options = [];
foreach ($configurationSources as $source) {
/* something happens here */
$options = array_merge($options, $source->getOptions());
}

以上代码可以优化成:

$options = [];
foreach ($configurationSources as $source) {
/* something happens here */
$options[] = $source->getOptions(); // <- yes, we'll use a little bit more memory
}

/* PHP below 5.6 */
$options = call_user_func_array('array_merge', $options + [[]]); // the nested empty array covers cases when no loops were made, must be second operand

/* PHP 5.6+: more friendly to refactoring as less magic involved */
$options = array_merge([], ...$options); // the empty array covers cases when no loops were made

/* PHP 7.4+: array_merge now accepts to be called without arguments. It will work even if $options is empty */
$options = array_merge(...$options);

参考地址

https://github.com/kalessil/phpinspectionsea/blob/master/docs/performance.md#slow-array-function-used-in-loop