2014年5月2日 星期五

[PHP] 轉換資料 Ⅱ:for-loop vs. array_reduce()

/**
 * Origin:
 *  array(
 *    array('id' => 'x', 'name' => 'apple'),
 *    array('id' => 'y', 'name' => 'banana'),
 *    array('id' => 'z', 'name' => 'orange'),
 *  );
 * Expect:
 *  array(
 *    'x' => 'apple',
 *    'y' => 'banana',
 *    'z' => 'orange',
 *  );
 */
function calc($t0, $t1)
{
   $v0 = array_sum(explode(' ', $t0));
   $v1 = array_sum(explode(' ', $t1));
   $sub = $v1 - $v0;
   echo "$v1 - $v0 = $sub\n";
   return $sub;
}

$origin = array(
   array('id' => 'x', 'name' => 'apple'),
   array('id' => 'y', 'name' => 'banana'),
   array('id' => 'z', 'name' => 'orange'));

$t0 = microtime();
for ($i = 0; $i < 1E6; $i++) {
   $expect = array();
   foreach ($origin as $o) {
      $expect[$o['id']] = $o['name'];
   }
}
$t1 = microtime();
$method1 = calc($t0, $t1);     // output: 1420770579.8306 - 1420770578.0456 = 1.785040140152

$t0 = microtime();
for ($i = 0; $i < 1E6; $i++) {
   $expect = array_reduce($origin, function ($result, $item) {
      $result[$item['id']] = $item['name']; return $result; });
}
$t1 = microtime();
$method2 = calc($t0, $t1);     // output: 1420770588.2167 - 1420770579.8308 = 8.3859748840332

echo ($method2 - $method1) / $method2; // output: 0.78713981798936

從測試中可以知道,使用 array_reduce() 比之 for-loop 較慢,雖然看起來比較簡潔。

PHP 5.3.24 (cli) (built: Jun 10 2013 16:42:20)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2013 Zend Technologies
    with Xdebug v2.2.0rc1, Copyright (c) 2002-2012, by Derick Rethans

沒有留言:

張貼留言

[Java] Invalid HTTP method: PATCH

最近系統需要使用 Netty4,所以把衝突的 Netty3 拆掉,然後就出現了例外。 pom.xml <dependency> <groupId>com.ning</groupId> <artifactId>as...