array_merge VS直接阵列注入性能

array_merge VS direct array injection performance

它们之间在性能或任何方面有什么不同吗?

$a = ['a' => 1, 'b' => 2, 'c' => 3];
$b = ['d' => 4, 'e' => 5, 'f' => 6];
$c = array_merge($a, $b);

VS

$a = [];
$a['a'] = 1;
$a['b'] = 2;
$a['c'] = 3;

$b = [];
$b['d'] = 4;
$b['e'] = 5;
$b['f'] = 6;
$c = array_merge($a, $b);

VS

$a = [];
$a = ['a' => 1, 'b' => 2, 'c' => 3];
$a['d'] = 4;
$a['e'] = 5;
$a['f'] = 6;

首先,像这样的微优化通常是没有意义的,除非您有大量的请求要处理或有非常大的数据集。话虽这么说...

选项 1 和选项 2 的性能应该大致相同。但是,第一个选项会稍微快一些,因为不需要动态扩展数组 A 和数组 B,而这在第二个示例中是必需的。

然而,前两个示例都使用了 array_merge(),这引入了实际进行函数调用的开销,并且仍然需要检查密钥是否实际存在。请注意,array_merge 会覆盖与字符串键关联的元素(当该键已存在时)。但是请记住,如果元素带有数字键,则不会这样做。在那种情况下,没有这样的检查,也没有任何东西被覆盖;键和元素只是简单地附加到目标数组的末尾。这是 PHP 文档解释:

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. Values in the input arrays with numeric keys will be renumbered with incrementing keys starting from zero in the result array. https://www.php.net/manual/en/function.array-merge.php

当然,使用array_merge()的好处就是一看就知道是干什么的。

这是我的基准测试,它比较了直接将 $b 的项目插入 $a 与合并 $a$b 以使用 [=11= 创建一个新数组].两个初始数组中都有 100 万个项目。

<?php


$a = [];
$b = [];

/*Insert 1000000 elements into array $a with string keys starting at '0' and ending at '999999'*/
for ($i = 0; $i < 1000000; $i++)
{
  $a["{$i} "] = $i;
}

/*Insert 1000000 elements into array $b with string keys starting at '1000000' and ending at '1999999' */
for ($j = 1000000; $j < 2000000; $j++)
{
  $b["{$j} "] = $j;
}


$temp = $a;

/*Inserting the values of $b into $temp in a loop*/
$start = microtime(true);
foreach($b as $key => $current)
{
   $temp[$key] = $current;  
}   

$end = microtime(true);
$runtime = $end - $start;
$output =  "<p>Inserted elements of array a and b with assignment in %.10f ({$runtime}) seconds</p>";

echo sprintf($output, $runtime);



/*Using array_merge to merge $a and $b */   
$start = microtime(true);

$c = array_merge($a, $b);

$end = microtime(true);


$runtime = $end - $start;
$output =  "<p>Merged array a and b with array_merge() in %.10f  ({$runtime}) seconds </p>";

echo sprintf($output, $runtime);

输出:

在 0.1125514507 (0.11255145072937) 秒内插入数组 a 和 b 的元素并赋值

在 0.0289690495 (0.028969049453735) 秒内用 array_merge() 合并了数组 a 和 b。

我修改了基准测试,所以它在赋值测试中使用了一个临时数组,这样 $a 和 $b 永远不会被修改。然而,运行ning 时间的差异仍然存在。为了得到一个好的平均值,我 运行 它 1000 次,取两次 运行ning 次的平均值。最终结果与最初的 运行 没有太大区别。第一种方法的平均时间约为 0.1012 秒,而 merge_array() 方法耗时 0.0574 秒。这相差大约 0.0438 秒或 43.8 毫秒。

因此,您看到的平均性能差异约为 57%。这很有趣,因为我发现 array_merge() 在旧版本的 PHP 中很慢。但是,从 7.3 开始,看起来应该选择 array_merge() 而不是手动合并带有字符串键的数组。