📜 ⬆️ ⬇️

PHP - optimization of multiple array_merge ()

A little hint, which I am going to tell you now, I learned a long time ago. But, since I just discovered that it was in this place that the optimization helped 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).

I'll be brief, here's a test script and what it prints:

$ 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 "It is 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.


Savings solid. Perhaps someone come in handy.

Source: https://habr.com/ru/post/101608/


All Articles