LEN

array_walk, array_map, foreach 性能测试比较
<?php $chatbar_admin_list = array_combine(range(100000...
扫描右侧二维码阅读全文
21
2017/08

array_walk, array_map, foreach 性能测试比较

<?php
$chatbar_admin_list = array_combine(range(100000, 199999), range(200000, 299999));

$key_list = array_keys($chatbar_admin_list);
$start1_time = microtime_float();

$chatbar_new_admin_list = array();
array_walk($chatbar_admin_list, function ($value, $key) use (&$chatbar_new_admin_list) {
    $chatbar_new_admin_list[$value][] = $key;
}, $key_list);

$end1_time = microtime_float();
echo 'array_walk :' . count($chatbar_new_admin_list). '; time :'. ($end1_time - $start1_time) ,PHP_EOL;

unset($chatbar_new_admin_list);
echo '------------------------------------------------------------------------------',PHP_EOL;

$start2_time = microtime_float();

array_map(function($value, $key) use (&$chatbar_new_admin_list) {
    $chatbar_new_admin_list[$value][] = $key;
}, $chatbar_admin_list, $key_list);

$end2_time = microtime_float();
echo 'array_map  :' . count($chatbar_new_admin_list). '; time :'. ($end2_time - $start2_time) ,PHP_EOL;

unset($chatbar_new_admin_list);
echo '------------------------------------------------------------------------------',PHP_EOL;


$start_time = microtime_float();
$chatbar_new_admin_list = array();
foreach ($chatbar_admin_list as $key => $value) {
    $chatbar_new_admin_list[$value][] = $key;
}
$end_time = microtime_float();
echo 'foreach    :' . count($chatbar_new_admin_list). '; time :'. ($end_time - $start_time) ,PHP_EOL;


//时间计算
function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

下面分别是在php7 和 php5.5 环境下的测试

[root@## ~]#php7 test.php 
array_walk :100000; time :0.065828084945679
------------------------------------------------------------------------------
array_map  :100000; time :0.033947944641113
------------------------------------------------------------------------------
foreach    :100000; time :0.016152143478394

[root@## ~]#php test.php 
array_walk :100000; time :0.1187047958374
------------------------------------------------------------------------------
array_map  :100000; time :0.14281415939331
------------------------------------------------------------------------------
foreach    :100000; time :0.047125816345215

在我当前测试场景下 foreach 性能碾压 array_walk, array_map 函数..

Last modification:August 21st, 2017 at 05:48 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment