2014年4月3日 星期四

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

/**
 * Origin:
 *  array(
 *    array('id' => 'x'),
 *    array('id' => 'y'),
 *    array('id' => 'z'),
 *  );
 * Expect:
 *  array('x', 'y', 'z');
 */
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'), array('id' => 'y'), array('id' => 'z'));

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

$t0 = microtime();
for ($i = 0; $i < 1E6; $i++) {
   $expect = array_map(function ($o) { return $o['id']; }, $origin);
}
$t1 = microtime();
$method2 = calc($t0, $t1);     // output: 1420770202.2368 - 1420770195.0461 = 7.1907830238342

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

從測試中可以知道 array_map() 比 for-loop 慢。不過 array_map() 寫法比較簡潔。

補充,引用外部參數:

   $key = 'id';
   $expect = array_map(function ($o) use ($key) { return $o[$key]; }, $origin);
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...