Advertisement
arxeiss

Benchmark custom merge vs array_replace

Jun 27th, 2019
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.08 KB | None | 0 0
  1. <?php
  2.  
  3. function customMerge(array ...$arrays) {
  4.     $all = [];
  5.     foreach ($arrays as $array) {
  6.         foreach ($array as $key => $value) {
  7.             $all[$key] = $value;
  8.         }
  9.     }
  10.  
  11.     return $all;
  12. }
  13.  
  14. $first = [
  15.     'key' => 'value',
  16.     111 => 'chuck norris',
  17. ];
  18.  
  19. $second = [
  20.     666 => 'hi',
  21.     333 => 'hello world',
  22. ];
  23.  
  24. $third = [
  25.     'key' => 'another value',
  26.     999 => 'chuck norris',
  27. ];
  28.  
  29. foreach (['first', 'second', 'third'] as $name) {
  30.     for ($i=0; $i < 700; $i++) {
  31.         $ai = rand(1,999);
  32.         ${$name}[$ai] = rand(10000,99999);
  33.     }
  34. }
  35.  
  36.  
  37. $iterations = 50000;
  38.  
  39. $a = microtime(true);
  40. for ($i = 0; $i < $iterations; $i++) {
  41.     array_replace($first, $second, $third);
  42. }
  43. printf('array_replace (%dx): %.2fs%s', $iterations, microtime(true) - $a, PHP_EOL);
  44.  
  45. $b = microtime(true);
  46. for ($i = 0; $i < $iterations; $i++) {
  47.     customMerge($first, $second, $third);
  48. }
  49. printf('customMerge (%dx): %.2fs%s', $iterations, microtime(true) - $b, PHP_EOL);
  50.  
  51. // Final Output:
  52. // array_replace (50000x): 1.15s
  53. // customMerge (50000x): 17.43s
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement