简体   繁体   English

PHP array_merge 与 foreach 循环

[英]PHP array_merge vs foreach loop

I was working on a Laravel project.我正在研究 Laravel 项目。 Where I had to marge 3 arrays.我必须在哪里marge 3 arrays。 Array sizes may be big or empty.数组大小可能很大或为空。 Firstly my concept was using首先我的概念是使用

array_merge($first_array, $second_array, $third_array)

FYI array has only numbers.仅供参考,数组只有数字。 One array element may belong to another array.一个数组元素可能属于另一个数组。 I don't need to remove duplicates or sort arrays.我不需要删除重复项或对 arrays 进行排序。 But it is mandatory that the first array data must be first on merged_array.但强制第一个数组数据必须在merged_array 上。

Somehow it wasn't performing well.不知怎的,它的表现并不好。 Then I wrote this code there.然后我在那里写了这段代码。

foreach ($array2 as $i) { $array1[] = $i; }

Now my curiosity is which code is faster or efficient.现在我的好奇心是哪个代码更快或更高效。 With large data or less data.有大数据或更少数据。

My experience with我的经历

  • 10k data (sum of 3 arrays) 10k 数据(3 个数组的总和)
  • 1k data (sum of 3 arrays) 1k 数据(3 个数组的总和)

Results结果

  • 1 no results 1 没有结果

    • array_merge takes time of n array_merge 需要 n 的时间
    • foreach takes time of sqrt(n) foreach 需要时间 sqrt(n)
  • 2 no results 2 没有结果

    • array_merge takes time of n array_merge 需要 n 的时间
    • foreach takes time of n^2 foreach 需要 n^2 的时间

Actually it depends on server PC config.实际上它取决于服务器PC配置。 When server PC RAM is free (no cache), it works fine.当服务器 PC RAM 空闲(无缓存)时,它工作正常。 otherwise it don't show real answer (time complexity).否则它不会显示真正的答案(时间复杂度)。 I had found my own answer later.后来我找到了自己的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM