3

Which is faster array_merge or array_splice to merge arrays? (using array_splice to replace nothing with the 2nd array which has the effect of merging)

array_splice looks like it might use less array copying and as a result it might be faster. Is there any research on this point?

e.g.

array_splice($a1, count($a1), 0, $a2);
$a1 = array_merge($a1, $a2); 
6
  • The 2 functions doing not the same. One merges arrays the other splices! So what do you want to know? Commented Feb 20, 2017 at 14:27
  • 1
    How about benchmarking it specifically for your use case…?! Commented Feb 20, 2017 at 14:28
  • @JustOnUnderMillions I assume he's using array_splice() without removing anything, just splicing the new array at the end. Commented Feb 20, 2017 at 14:28
  • @Barmar year you are right, i thing the OP should ignore it, its only micro-optimizing. Commented Feb 20, 2017 at 14:30
  • @Barmar Yes, that's right. Splicing without removing anything would have the effect of merging. Apologies for the lack of clarity in the question. I'll edit to make that clear. (even if it is a micro-optimisation question, the rating of -4 does seem a bit unwarranted) Commented Feb 21, 2017 at 0:57

2 Answers 2

2

array_merge has to check whether the input array has numeric or named keys, so it knows whether to append or merge. array_splice doesn't need to do this check.

Sign up to request clarification or add additional context in comments.

Comments

1
$arguments = ["arg1" => "111", "arg2" => "222", "arg3" => "333"];

Use array_splice = 3.273508 (in seconds)

for ($i=0; $i < 1000000; $i++) { 
   $arguments = ["arg1" => "111", "arg2" => "222", "arg3" => "333"];
   array_splice($arguments, 0, 0,[777]);
   $arguments = [];
}

Note* array_splice($arguments, count($arguments), 0,[777]); Same time as array_splice($arguments, 0, 0,[777]); = ~3.273508 (in seconds)

Output

Array
(
    [0] => 777
    [arg1] => 111
    [arg2] => 222
    [arg3] => 333
)

Use array_merge = 2.984012 (in seconds)

for ($i=0; $i < 1000000; $i++) { 

    $arguments = ["arg1" => "111", "arg2" => "222", "arg3" => "333"];
    $args = array_merge([777], $arguments);
    $arguments = [];
}

Output

Array
(
    [0] => 777
    [arg1] => 111
    [arg2] => 222
    [arg3] => 333
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.