fork download
  1. <?php
  2. function item_array_key_exists($a, $buscado) {
  3. if(!is_array($a)) return NULL;
  4. return array_key_exists($buscado,$a)?$v[$buscado]:0;
  5. }
  6. function foreach_inc($a, $buscado) {
  7. if(!is_array($a)) return NULL;
  8. $i=0;
  9. foreach($a as $v)
  10. if($buscado===$v)
  11. $i++;
  12. return $i;
  13. }
  14.  
  15.  
  16.  
  17. $names = ['item_array_key_exists', 'foreach_inc'];
  18. $loops = 10000;
  19. $arr_rand_items = 500;
  20. $arr_repeated = 3;
  21. $a = [];
  22.  
  23.  
  24.  
  25. //Generar array de strings random
  26. function generateRandomString($length = 10) {
  27. $characters = 'abcdefghijklmnopqrstuvwxyz';
  28. $charactersLength = strlen($characters);
  29. $randomString = '';
  30. for ($i = 0; $i < $length; $i++) {
  31. $randomString .= $characters[rand(0, $charactersLength - 1)];
  32. }
  33. return $randomString;
  34. }
  35. for ($i = 0; $i < $arr_rand_items; $i++)
  36. $a[] = generateRandomString();
  37.  
  38. //Multiplicar el array
  39. $aux = $a;
  40. for ($i = 0; $i < $arr_repeated - 1; $i++)
  41. $a = array_merge($a, $aux);
  42.  
  43. $item_buscado = $a[array_rand($a)];
  44.  
  45. $params = array($a, $item_buscado);
  46.  
  47.  
  48. function speed_test($code, $loops = 500000, $params = []) {
  49. $before = microtime(true);
  50. for ($i=0 ; $i<$loops ; $i++) {
  51. $code($params[0],$params[1]);
  52. }
  53. $after = microtime(true);
  54. $delay = $after-$before;
  55. return $delay;
  56. }
  57. $best = 999999999;
  58. $worst = 0;
  59. $best_num = -1;
  60.  
  61.  
  62. foreach ($names as $code_num => $f)
  63. {
  64. $delay = speed_test($f, $loops, $params);
  65. if ($delay < $best) {
  66. $best = $delay;
  67. $best_num = $code_num;
  68. }
  69. if ($delay > $worst) {
  70. $worst = $delay;
  71. }
  72. echo "Code #" . ($code_num + 1) . "($names[$code_num]): \t" . number_format($delay, 2) . " secs/" . $loops/1E3 . "k loops\n";
  73. }
  74. echo "BEST: $names[$best_num] by " . number_format((1- $best / $worst) * 100, 0) . "%";
Success #stdin #stdout 2.36s 52488KB
stdin
Standard input is empty
stdout
Code #1(item_array_key_exists): 	1.03 secs/10k loops
Code #2(foreach_inc): 	1.31 secs/10k loops
BEST: item_array_key_exists by 22%