quocvuongdn

Benchmark array_walk vs. for: Find multiple keys in an array

Mar 10th, 2017
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.09 KB | None | 0 0
  1. <?php
  2. function get_multiple_keys($arr, $keys = []){
  3.   $result = [];
  4.   array_walk($keys, function($key, &$val = null) use ($arr, &$result){
  5.       if(isset($arr[$key])){
  6.           $result[$key] = $arr[$key];
  7.       }
  8.   });
  9.   return $result;
  10. }
  11. // C.1
  12. for($i = 0; $i < 1000; $i++){
  13.   $src["randzz{$i}"] = [
  14.       'name' => "V{$i}",
  15.       'cnt' => $i
  16.   ];
  17. }
  18. for($i = 0; $i < 10; $i++){
  19.   $ind = rand(0, 2000);
  20.   $finds[] = "randzz{$ind}";
  21. }
  22. $start1 = microtime(true)*1000;
  23. $test1 = get_multiple_keys($src, $finds);
  24. $end1 = microtime(true)*1000;
  25. echo $end1- $start1.PHP_EOL;
  26. echo count($test1).'<br/>';
  27. /*============*/
  28. // C.2
  29. $start2 = microtime(true)*1000;
  30. /* for($i = 0; $i < 10; $i++){
  31.  $ind = rand(0, 2000);
  32.   if(isset($src["{$ind}"])){
  33.     $test2[] = $src["{$ind}"];
  34.   }
  35. } */
  36. for($i = 0; $i < count($finds); $i++){
  37.   $ind = $finds[$i];
  38.   if(isset($src["{$ind}"])){
  39.       $test2[] = $src["{$ind}"];
  40.   }
  41. }
  42. $end2 = microtime(true)*1000;
  43. echo $end2- $start2.PHP_EOL;
  44. echo count($test2).PHP_EOL;
  45. // Result
  46. // C.1
  47. // 0.072998046875 ; count 4
  48. // C.2
  49. // 0.02197265625 ; count 4
Advertisement
Add Comment
Please, Sign In to add comment