在 100000 次循环的测试中,我得到了这样的结果:
bin/php-test CloneVsNew
[============================================================>] 100000 u | 4399 u/s | Est: 0.0 s | Mem: 342,74 KB | Max: 367,1 KB
[============================================================>] 100000 u | 4105 u/s | Est: 0.0 s | Mem: 343,14 KB | Max: 367,1 KB
New 1,282884 sec.
Clone 1,107343 sec.
因此,似乎 clone 复制对象的方式稍微有效一些。这是测试代码:
class CloneVsNew extends TestApplication
{
final public static function run()
{
$repeats = 100000;
$bar = new CliProgressBar($repeats);
for ($i = 0; $i <= $repeats; ++$i) {
Timer::start();
$myobj1=new \stdClass();
$myobj2=new \stdClass();
$myobj3=new \stdClass();
$myobj4=new \stdClass();
Timer::stop();
$bar->update($i);
}
self::addResult('New', Timer::get());
$bar = new CliProgressBar($repeats);
Timer::reset();
for ($i = 0; $i <= $repeats; ++$i) {
Timer::start();
$myobj1 = new \stdClass();
$myobj2 = clone $myobj1;
$myobj3 = clone $myobj1;
$myobj4 = clone $myobj1;
Timer::stop();
$bar->update($i);
}
self::addResult('Clone', Timer::get());
}
}
测试:
php -v
PHP 5.4.17-1~dotdeb.1 (cli) (built: Jul 6 2013 16:20:31)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2013 Zend Technologies
with Xdebug v2.2.3, Copyright (c) 2002-2013, by Derick Rethans
其他 php 版本可以显示其他结果。
更新:
对于测试使用php-bench工具。