array_walk、array_map 和 foreach, for 的效率的比较

Jackey PHP 4,616 次浏览 , 没有评论
  1. //产生一个10000的一个数组。
  2. $max = 10000;
  3. $test_arr = range(0, $max);
  4. $temp = 0;
  5. //我们分别用三种方法测试求这些数加上1的值的时间。
  6.  
  7. // for 的方法
  8. $t1 = microtime(true);
  9. for ($i = 0; $i < $max; $i++) {
  10. $temp = $temp + 1;
  11. }
  12. $t2 = microtime(true);
  13. $t = $t2 - $t1;
  14. echo "就使用for, 没有对数组操作 花费: {$t}<br>";
  15.  
  16. $t1 = microtime(true);
  17. for ($i = 0; $i < $max; $i++) {
  18. $test_arr[$i] = $test_arr[$i] + 1;
  19. }
  20. $t2 = microtime(true);
  21. $t = $t2 - $t1;
  22. echo "使用for 并且直接对数组进行了操作 花费: {$t}<br>";
  23.  
  24. $t1 = microtime(true);
  25. for ($i = 0; $i < $max; $i++) {
  26. addOne($test_arr[$i]);
  27. }
  28. $t2 = microtime(true);
  29. $t = $t2 - $t1;
  30. echo "使用for 调用函数对数组操作 花费 : {$t}<br>";
  31.  
  32. $t1 = microtime(true);
  33. foreach ($test_arr as $k => &$v) {
  34. $temp = $temp + 1;
  35. }
  36. $t2 = microtime(true);
  37. $t = $t2 - $t1;
  38. echo "使用 foreach 没有对数组操作 花费 : {$t}<br>";
  39.  
  40. $t1 = microtime(true);
  41. foreach ($test_arr as $k => &$v) {
  42. $v = $v + 1;
  43. }
  44. $t2 = microtime(true);
  45. $t = $t2 - $t1;
  46. echo "使用 foreach 直接对数组操作 : {$t}<br>";
  47.  
  48. $t1 = microtime(true);
  49. foreach ($test_arr as $k => &$v) {
  50. addOne($v);
  51. }
  52. $t2 = microtime(true);
  53. $t = $t2 - $t1;
  54. echo "使用 foreach 调用函数对数组操作 : {$t}<br>";
  55.  
  56. $t1 = microtime(true);
  57. array_walk($test_arr, 'addOne');
  58. //array_walk($test_arr,
  59. // function ($item, $key) use (&$test_arr) {
  60. // $test_arr[$key] = $item + 1;
  61. //});
  62. $t2 = microtime(true);
  63. $t = $t2 - $t1;
  64. echo "使用 array_walk 花费 : {$t}<br>";
  65.  
  66. $t1 = microtime(true);
  67. $result = array_map(function ($val) {
  68. return $val + 1;
  69. }, $test_arr);
  70. $t2 = microtime(true);
  71. $t = $t2 - $t1;
  72. echo "使用 array_map 花费 : {$t}<br>";
  73.  
  74. function addOne(&$item) {
  75. $item = $item + 1;
  76. }

运行结果:

就使用for, 没有对数组操作 花费: 0.00025606155395508
使用for 并且直接对数组进行了操作 花费: 0.00042009353637695
使用for 调用函数对数组操作 花费 : 0.00097513198852539
使用 foreach 没有对数组操作 花费 : 0.00043892860412598
使用 foreach 直接对数组操作 : 0.00044989585876465
使用 foreach 调用函数对数组操作 : 0.00089097023010254
使用 array_walk 花费 : 0.00073599815368652
使用 array_map 花费 : 0.0004730224609375

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Go