2018年5月28日 星期一

[PHP] unique values & resort keys

function calc($t0, $t1)
{
    $v0 = array_sum(explode(' ', $t0));
    $v1 = array_sum(explode(' ', $t1));
    $sub = $v1 - $v0;
    echo "$v1 - $v0 = $sub\n";
    return $sub;
}

$a = [116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,116,117,116,117,116,116,116,116,116,119];

$t0 = microtime();
for ($i = 0; $i < 1E6; $i++) {
    array_values(array_unique($a));
}
$t1 = microtime();
$method1 = calc($t0, $t1);     // output: 1527477436.7125 - 1527477409.434 = 27.278562068939

$t0 = microtime();
for ($i = 0; $i < 1E6; $i++) {
    array_keys(array_flip($a));
}
$t1 = microtime();
$method2 = calc($t0, $t1);     // output: 1527477439.6214 - 1527477436.7126 = 2.908814907074

$t0 = microtime();
for ($i = 0; $i < 1E6; $i++) {
    array_merge(array_flip(array_flip($a)));
}
$t1 = microtime();
$method3 = calc($t0, $t1);     // output: 1527477443.3256 - 1527477439.6215 = 3.7041912078857

有時候直覺的方式會比較慢。

參考資料:http://php.net/manual/en/function.array-unique.php#70786

PHP 5.6.36 (cli) (built: May  9 2018 20:31:47)
Copyright (c) 1997-2016 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies
    with Xdebug v2.3.3, Copyright (c) 2002-2015, by Derick Rethans

沒有留言:

張貼留言

[Java] Invalid HTTP method: PATCH

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