array_merge vs array_value用于重置数组索引

I have 1 array that I want to re-index. I have found that both array_values and array_merge functions can do the job (and I don't need 2 arrays for the array_merge function to work).

Which is faster for a very large array? I would benchmark this, but I don't know how and don't have the large array yet.

Before re-index:

    [0] => AB
    [4] => EA
    [6] => FA
    [9] => DA
    [10] => AF

After re-index:

    [0] => AB
    [1] => EA
    [2] => FA
    [3] => DA
    [4] => AF
duanlao6573 我得到了替补标记,array_value快了3倍,8043元素数组的数组值为0.003291130065918秒。阵列合并花了0.0096800327301025秒。$shuf是未编入索引的数组下面是运行基准测试的代码(从网上复制)$sha1_start=microtime(true);$arraymerge=array_merge($shuf);$shal_elapsed=microtime(true)-$sha1_start;$start=microtime(true);$arrayvalue=array_values($shuf);$elapsed=microtime(true)-$start;echo“<br>数组值耗时$秒。”;echo“<br>arraymerge花了$shal_elapsed秒。”;
10 年多之前 回复


我还没有完成基准测试 - 如果你需要确定,你应该这样做。</ p> \ n

那就是说,我怀疑如果一个比另一个好,那么array_values()将是最佳选择。 </ p>

毕竟,你想要做的就是为array_values()设计的。</ p>
</ div>



I haven't done the benchmarks either -- and if you need to be sure, you should do them.

That said, I would suspect that if one is preferable to the other, array_values() is going to be the way to go.

After all, what you want to do is exactly what array_values() was designed for.

重要的是要注意 array_merge()</ code>只会在没有字符串键的情况下重置数组键 数组。</ p>
</ div>



It's important to note that array_merge() will only reset the array keys if there are no string keys in the array.

array_merge是为了做其他事情,你有一个解决方法来制作 它适用于你的情况。 (尽管如果索引中忘记了非数值,你可能会遇到问题)。</ p>

我不知道是否存在显着的性能差异,但确保用array_values编写的代码更容易 阅读。 而且我认为一个意味着做某事的功能比想要做某事的功能慢。</ p>

希望这会有所帮助。</ p>
</ div>



array_values is meant to do exactly what you want it to do. array_merge is meant to do something else and you got a workaround to make it work on your case. (although you might have problems if a non-numerical value is forgotten in the indexes).

I don't know if there are significant performance differences but for sure code written with array_values is easier to read. And I don't think that a function that is meant to do something is slower than one meant to do something else.

Hope this helps.

I got the bench mark, array_value is 3x faster (sorry to answer my own question, the comment section does not retain the format)

for and array with 8043 elements

array values took 0.003291130065918 seconds.

array merge took 0.0096800327301025 seconds.

$shuf is the un-indexed array

Below is the code for running the benchmark (copied it off the web)

    $sha1_start = microtime(true); 
    $arraymerge = array_merge ($shuf); 
    $shal_elapsed = microtime(true) - $sha1_start;

    $start = microtime(true); 
    $arrayvalue = array_values ($shuf); 
    $elapsed = microtime(true) - $start;

echo "<br>array values took $elapsed seconds."; 
echo "<br>array merge took $shal_elapsed seconds.";
dongqian1893 谢谢你的澄清! 也许你可以接受这个作为答案:)
接近 3 年之前 回复
Csdn user default icon