PHP - optimizing multiple array_merge ()

    A small hint that I am going to talk about now, I learned for quite some time. But, since I just discovered that it was in this place that optimization helped to save a fair amount of time already in the current project, I decided to share it with the public (and the men don’t know, yeah).

    To be brief, here is a test script and what it outputs:

    $ start = microtime (true);
    $ res1 = array ();
    for ($ i = 0; $ i <1000; $ i ++) {
            $ res1 = array_merge ($ res1, array (1, 2, 3));
    }
    echo "1000 merges:". ceil ((microtime (true) - $ start) * 1000). "ms \ n";
     
    $ start = microtime (true);
    $ toMerge = array ();
    for ($ i = 0; $ i <1000; $ i ++) {
            $ toMerge [] = array (1, 2, 3); 
    }
    $ res2 = call_user_func_array ('array_merge', $ toMerge);
    echo "call_user_func_array ('array_merge', ..):". ceil ((microtime (true) - $ start) * 1000). "ms \ n";
     
    echo "Is it true that the two arrays are equal? ​​It is";
    var_export ($ res2 === $ res1);
    echo ". \ n";

    ~ % php ~/tmp/array_merge.php
    1000 merges: 980ms
    call_user_func_array('array_merge',..): 11ms
    Is it true that the two arrays are equal? It is true.


    The savings are substantial. Maybe someone will come in handy.

    Also popular now: