merge two arrays, merge-sort style

后端 未结 1 1055
隐瞒了意图╮
隐瞒了意图╮ 2020-12-18 08:20

Suppose I have two arrays:

$a1 = array(0,1,2);
$a2 = array(3,4,5);

I want to be able to do a merge that alternates the arrays and not conca

相关标签:
1条回答
  • 2020-12-18 09:05
    $count = count($a1);
    for ($i = 0; $i < $count; $i++) {
        $newArray[] = $a1[$i];
        $newArray[] = $b1[$i];
    }
    

    My work here is done.

    $a1 = array(0,1,2);
    $a2 = array(3,4,5);
    
    $start = microtime(TRUE);
    
    for($t = 0; $t < 100000; $t++)
    {
        $newArray = array();
        $count = count($a1);
        for ($i = 0; $i < $count; $i++)
        {
            $newArray[] = $a1[$i];
            $newArray[] = $a2[$i];
        }
    }
    echo  round(microtime(TRUE) - $start, 2); # 0.6
    
    $a1 = array(0,1,2);
    $a2 = array(3,4,5);
    
    $start = microtime(TRUE);
    
    for($t = 0; $t < 100000; $t++)
    {
        $newArray = array();
        for ($i = 0; $i < count($a1); $i++)
        {
            $newArray[] = $a1[$i];
            $newArray[] = $a2[$i];
        }
    }
    echo  round(microtime(TRUE) - $start, 2); # 0.85
    

    So pre-counting array size will be ~1/4 [citation needed] (on freakin' 100.000 iterations you will gain 0.2 in total) faster. If you put count() inside loop, it will recount on every iteration. 1/4 seems to me a reasonably faster. If you are looking for compiled function, you can stop.

    P.S. Benchmark is like bikini, it shows you everything, and nothing.

    0 讨论(0)
提交回复
热议问题