quocvuongdn icon

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

quocvuongdn | PRO | 03/11/17 02:38:40 AM UTC | 0 ⭐ | 386 👁️ | Never ⏰ | []
PHP |

1.09 KB

|

None

|

0 👍

/

0 👎

<?php
function get_multiple_keys($arr, $keys = []){
  $result = [];
  array_walk($keys, function($key, &$val = null) use ($arr, &$result){
      if(isset($arr[$key])){
          $result[$key] = $arr[$key];
      } 
  });
  return $result;
}
// C.1
for($i = 0; $i < 1000; $i++){
  $src["randzz{$i}"] = [
      'name' => "V{$i}",
      'cnt' => $i
  ];
}
for($i = 0; $i < 10; $i++){
  $ind = rand(0, 2000);
  $finds[] = "randzz{$ind}";
}
$start1 = microtime(true)*1000;
$test1 = get_multiple_keys($src, $finds);
$end1 = microtime(true)*1000;
echo $end1- $start1.PHP_EOL;
echo count($test1).'<br/>';
/*============*/
// C.2
$start2 = microtime(true)*1000;
/* for($i = 0; $i < 10; $i++){
 $ind = rand(0, 2000);
  if(isset($src["{$ind}"])){
    $test2[] = $src["{$ind}"];
  }
} */
for($i = 0; $i < count($finds); $i++){
  $ind = $finds[$i];
  if(isset($src["{$ind}"])){
      $test2[] = $src["{$ind}"];
  }
}
$end2 = microtime(true)*1000;
echo $end2- $start2.PHP_EOL;
echo count($test2).PHP_EOL;
// Result
// C.1
// 0.072998046875 ; count 4
// C.2
// 0.02197265625 ; count 4

Comments