Advertisement
ekho

isset vs array_key_exists

Oct 16th, 2012
116
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.45 KB | None
  1. <?php
  2.  
  3. function prepare($num) {
  4.     echo "preparing array with $num elements ... ";
  5.     $array = array();
  6.     for ($i=0; $i<$num; $i++) {
  7.         $array[uniqid('', true)] = true;
  8.     }
  9.     echo 'OK', PHP_EOL;
  10.     return $array;
  11. }
  12.  
  13. function test($num, $cycles, $tries) {
  14.     echo "@cycles: ", $cycles, PHP_EOL;
  15.     echo "@length: ", $num, PHP_EOL;
  16.     echo "@tries: ", $tries, PHP_EOL;
  17.  
  18.     $array = prepare($num);
  19.     $key = uniqid('', true);
  20.  
  21.     echo "array_key_exists: ";
  22.     $times = array();
  23.     for ($j=0; $j<$tries; $j++) {
  24.         $t = microtime(true);
  25.         for($i = 0; $i < $cycles; $i++) {
  26.             array_key_exists($key, $array);
  27.         }
  28.         $times[$j] = microtime(true) - $t;
  29.     }
  30.     printf('%0.4f second(s)'.PHP_EOL, array_sum($times)/$tries);
  31.  
  32.     echo "isset: ";
  33.     $times = array();
  34.     for ($j=0; $j<$tries; $j++) {
  35.         $t = microtime(true);
  36.         for($i = 0; $i < $cycles; $i++) {
  37.             isset($array[$key]);
  38.         }
  39.         $times[$j] = microtime(true) - $t;
  40.     }
  41.     printf('%0.4f second(s)'.PHP_EOL, array_sum($times)/$tries);
  42. }
  43.  
  44. $cycles = 1000000;
  45. $tries = 5;
  46.  
  47. echo '----------------------', PHP_EOL;
  48. test(1000, $cycles, $tries);
  49. echo '----------------------', PHP_EOL;
  50. test(10000, $cycles, $tries);
  51. echo '----------------------', PHP_EOL;
  52. test(100000, $cycles, $tries);
  53. echo '----------------------', PHP_EOL;
  54. test(1000000, $cycles, $tries);
  55. echo '----------------------', PHP_EOL;
Advertisement
RAW Paste Data Copied
Advertisement