当前位置:Gxlcms > PHP教程 > 不要在循环体中使用array_merge()

不要在循环体中使用array_merge()

时间:2021-07-01 10:21:17 帮助过:31人阅读

标题是不要在循环体中使用 array_merge(),其实这只是本篇文章的结论之一

下面我们一起研究一下 php 语言中数组的合并(这里先不考虑递归合并)

四种合并数组的方式对比

四种常见的合并数组的方式对比

写代码

我们知道 array_merge() 和 运算符 + 都可以拼接数组

创建一个类

ArrayMerge()
● eachOne() 循环体使用 array_merge() 合并
● eachTwo() 循环体结束后使用 array_merge() 合并
● eachThree() 循环体嵌套实现数组合并
● eachFour() 循环体使用 运算符 + 拼接合并
● getNiceFileSize() 将内存占用转化成人类可读的方式

  1. /**
  2. * Class ArrayMerge
  3. */
  4. class ArrayMerge
  5. {
  6. /**
  7. * @param int $times
  8. * @return array
  9. */
  10. public static function eachOne(int $times): array
  11. {
  12. $a = [];
  13. $b = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  14. for ($i = 0; $i < $times; $i++) {
  15. $a = array_merge($a, $b);
  16. }
  17. return $a;
  18. }
  19. /**
  20. * @param int $times
  21. * @return array
  22. */
  23. public static function eachTwo(int $times): array
  24. {
  25. $a = [[]];
  26. $b = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  27. for ($i = 0; $i < $times; $i++) {
  28. $a[] = $b;
  29. }
  30. return array_merge(...$a);
  31. }
  32. /**
  33. * @param int $times
  34. * @return array
  35. */
  36. public static function eachThree(int $times): array
  37. {
  38. $a = [];
  39. $b = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  40. for ($i = 0; $i < $times; $i++) {
  41. foreach ($b as $item) {
  42. $a[] = $item;
  43. }
  44. }
  45. return $a;
  46. }
  47. /**
  48. * @param int $times
  49. * @return array
  50. */
  51. public static function eachFour(int $times): array
  52. {
  53. $a = [];
  54. $b = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  55. for ($i = 0; $i < $times; $i++) {
  56. $a = $b + $a;
  57. }
  58. return $a;
  59. }
  60. /**
  61. * 转化内存信息
  62. * @param $bytes
  63. * @param bool $binaryPrefix
  64. * @return string
  65. */
  66. public static function getNiceFileSize(int $bytes, $binaryPrefix = true): ?string
  67. {
  68. if ($binaryPrefix) {
  69. $unit = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB');
  70. if ($bytes === 0) {
  71. return '0 ' . $unit[0];
  72. }
  73. return @round($bytes / (1024 ** ($i = floor(log($bytes, 1024)))),
  74. 2) . ' ' . ($unit[(int)$i] ?? 'B');
  75. }
  76. $unit = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
  77. if ($bytes === 0) {
  78. return '0 ' . $unit[0];
  79. }
  80. return @round($bytes / (1000 ** ($i = floor(log($bytes, 1000)))),
  81. 2) . ' ' . ($unit[(int)$i] ?? 'B');
  82. }
  83. }

使用

先分配多点内存

输出内存占用,合并后的数组长度,并记录每一步的用时

  1. ini_set('memory_limit', '4000M');
  2. $timeOne = microtime(true);
  3. $a = ArrayMerge::eachOne(10000);
  4. echo 'count eachOne Result | ' . count($a) . PHP_EOL;
  5. echo 'memory eachOne Result | ' . ArrayMerge::getNiceFileSize(memory_get_usage(true)) . PHP_EOL;
  6. $timeTwo = microtime(true);
  7. $b = ArrayMerge::eachTwo(10000);
  8. echo 'count eachTwo Result | ' . count($b) . PHP_EOL;
  9. echo 'memory eachTwo Result | ' . ArrayMerge::getNiceFileSize(memory_get_usage(true)) . PHP_EOL;
  10. $timeThree = microtime(true);
  11. $c = ArrayMerge::eachThree(10000);
  12. echo 'count eachThree Result | ' . count($c) . PHP_EOL;
  13. echo 'memory eachThree Result | ' . ArrayMerge::getNiceFileSize(memory_get_usage(true)) . PHP_EOL;
  14. $timeFour = microtime(true);
  15. $d = ArrayMerge::eachFour(10000);
  16. echo 'count eachFour Result | ' . count($d) . PHP_EOL;
  17. echo 'memory eachFour Result | ' . ArrayMerge::getNiceFileSize(memory_get_usage(true)) . PHP_EOL;
  18. $timeFive = microtime(true);
  19. echo PHP_EOL;
  20. echo 'eachOne | ' . ($timeTwo - $timeOne) . PHP_EOL;
  21. echo 'eachTwo | ' . ($timeThree - $timeTwo) . PHP_EOL;
  22. echo 'eachThree | ' . ($timeFour - $timeThree) . PHP_EOL;
  23. echo 'eachFour | ' . ($timeFive - $timeFour) . PHP_EOL;
  24. echo PHP_EOL;

结果

  1. count eachOne Result | 100000
  2. memory eachOne Result | 9 MiB
  3. count eachTwo Result | 100000
  4. memory eachTwo Result | 14 MiB
  5. count eachThree Result | 100000
  6. memory eachThree Result | 18 MiB
  7. count eachFour Result | 10 #注意这里
  8. memory eachFour Result | 18 MiB
  9. eachOne | 5.21253490448 # 循环体中使用array_merge()最慢,而且耗费内存
  10. eachTwo | 0.0071840286254883 # 循环体结束后使用array_merge()最快
  11. eachThree | 0.037622928619385 # 循环体嵌套比循环体结束后使用array_merge()慢三倍
  12. eachFour | 0.0072360038757324 # 看似也很快,但是合并的结果有问题

● 循环体中使用 array_merge () 最慢,而且耗费内存

● 循环体结束后使用 array_merge () 最快

● 循环体嵌套比循环体结束后使用 array_merge () 慢三倍

● 看似也很快,但是合并的结果有问题

合并数组的坑

我们注意到刚刚的 eachFour 的结果长度只有 10

下面探究为什么会出现这样的结果

这里拿递归合并一起做下对比

代码

  1. public static function test(): void
  2. {
  3. $testA = [
  4. '111' => 'testA1',
  5. 'abc' => 'testA1',
  6. '222' => 'testA2',
  7. ];
  8. $testB = [
  9. '111' => 'testB1',
  10. 'abc' => 'testB1',
  11. '222' => 'testB2',
  12. 'www' => 'testB1',
  13. ];
  14. echo 'array_merge($testA, $testB) | ' . PHP_EOL;
  15. print_r(array_merge($testA, $testB));
  16. echo '$testA + $testB | ' . PHP_EOL;
  17. print_r($testA + $testB);
  18. echo '$testB + $testA | ' . PHP_EOL;
  19. print_r($testB + $testA);
  20. echo 'array_merge_recursive($testA, $testB) | ' . PHP_EOL;
  21. print_r(array_merge_recursive($testA, $testB));
  22. }

结果

+ 号拼接两个数组,后者只会补充前者没有的 key,但是会保留数字索引

array_merge() 和 array_merge_recursive() 会抹去数字索引,所有的数字索引按顺序从 0 开始了

  1. array_merge($testA, $testB) | #数字索引强制从0开始了 字符key相同的以后者为准
  2. Array
  3. (
  4. [0] => testA1
  5. [abc] => testB1
  6. [1] => testA2
  7. [2] => testB1
  8. [3] => testB2
  9. [www] => testB1
  10. )
  11. $testA + $testB | #testA得到保留,testB补充了testA中没有的key,数字索引得到保留
  12. Array
  13. (
  14. [111] => testA1
  15. [abc] => testA1
  16. [222] => testA2
  17. [www] => testB1
  18. )
  19. $testB + $testA | #testB得到保留,testA补充了testB中没有的key,数字索引得到保留
  20. Array
  21. (
  22. [111] => testB1
  23. [abc] => testB1
  24. [222] => testB2
  25. [www] => testB1
  26. )

array_merge_recursive($testA, $testB) | #数字索引从0开始连续了,但数组的顺序没有被破坏,相同的字符串 `key` 合并为一个数组

  1. Array
  2. (
  3. [0] => testA1
  4. [abc] => Array
  5. (
  6. [0] => testA1
  7. [1] => testB1
  8. )
  9. [1] => testA2
  10. [2] => testB1
  11. [3] => testB2
  12. [www] => testB1
  13. )

分析

看到这里,你一定非常疑惑,没想到 array_merge() 还有这样的坑

我们先来看一看官方的手册

  1. array_merge ( array $array1 [, array $... ] ) : array

array_merge () 将一个或多个数组的单元合并起来,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。

如果输入的数组中有相同的字符串键名,则该键名后面的值将覆盖前一个值。然而,如果数组包含数字键名,后面的值将不会覆盖原来的值,而是附加到后面。

如果只给了一个数组并且该数组是数字索引的,则键名会以连续方式重新索引。

只有相同的字符串键名,后边的值才会覆盖前面的值。(但是手册中没有解释为什么数字键名的索引被重置了)

那么我们来看一下源码

  1. PHPAPI int php_array_merge(HashTable *dest, HashTable *src)
  2. {
  3. zval *src_entry;
  4. zend_string *string_key;
  5. if ((dest->u.flags & HASH_FLAG_PACKED) && (src->u.flags & HASH_FLAG_PACKED)) {
  6. // 自然数组的合并,HASH_FLAG_PACKED表示数组是自然数组([0,1,2]) 参考http://ju.outofmemory.cn/entry/197064
  7. zend_hash_extend(dest, zend_hash_num_elements(dest) + zend_hash_num_elements(src), 1);
  8. ZEND_HASH_FILL_PACKED(dest) {
  9. ZEND_HASH_FOREACH_VAL(src, src_entry) {
  10. if (UNEXPECTED(Z_ISREF_P(src_entry)) &&
  11. UNEXPECTED(Z_REFCOUNT_P(src_entry) == 1)) {
  12. ZVAL_UNREF(src_entry);
  13. }
  14. Z_TRY_ADDREF_P(src_entry);
  15. ZEND_HASH_FILL_ADD(src_entry);
  16. } ZEND_HASH_FOREACH_END();
  17. } ZEND_HASH_FILL_END();
  18. } else {
  19. //遍历获取key和vaule
  20. ZEND_HASH_FOREACH_STR_KEY_VAL(src, string_key, src_entry) {
  21. if (UNEXPECTED(Z_ISREF_P(src_entry) &&
  22. Z_REFCOUNT_P(src_entry) == 1)) {
  23. ZVAL_UNREF(src_entry);
  24. }
  25. Z_TRY_ADDREF_P(src_entry);
  26. // 参考https://github.com/pangudashu/php7-internal/blob/master/7/var.md
  27. if (string_key) {
  28. // 字符串key(zend_string) 插入或者更新元素,会增加key的计数
  29. zend_hash_update(dest, string_key, src_entry);
  30. } else {
  31. //插入新元素,使用自动的索引值(破案了,索引被重置的原因在此)
  32. zend_hash_next_index_insert_new(dest, src_entry);
  33. }
  34. } ZEND_HASH_FOREACH_END();
  35. }
  36. return 1;
  37. }

总结

综上所述,合并数组的不同方式都存在一定的缺陷,但是通过我们上面的探究,我们了解到

● 循环体中使用 array_merge() 合并数组不可取,速度差距达百倍

● array_merge() 合并数组要慎用,如果重视 key ,且 key 可能为数字,不能使用 array_merge() 来合并,我们可以采用循环体嵌套的方式(注意内层循环使用 key 进行赋值操作)

● 如果重视 key ,且 key 可能为数字,简单合并数组可以使用运算符 + ,但是一定不要在循环体中使用,因为每次运算的的结果都是生成了一个新的数组

以上就是不要在循环体中使用 array_merge ()的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行