原型模式 clone 比 new 还慢?

win和linux的php测试

win: php7.4.4
linux: php7.2.29
不得不说,linuxwin快真多

文档「设计模式全集」- 原型模式   clone 比 new还慢?

文档「设计模式全集」- 原型模式

原本在看设计模式 - 原型模式,用phpunit测试下性能,

clone怎么比new还慢,又换成了php,还是一样的结果。
(内存消耗也是差不多的)

贴代码 复制粘贴即可运行 (展开再复制)

<?php

abstract class BookPrototype
{
  /**
 * @var string
 */  protected $title;

  /**
 * @var string
 */  protected $category;

  abstract public function __clone();

  public function getTitle(): string
  {
  return $this->title;
 }
  public function setTitle($title)
 {  $this->title = $title;
 }
}

class BarBookPrototype extends BookPrototype
{
  /**
 * @var string
 */  protected $category = 'Bar';

  public function __clone()
 { }}

function toMillisecond($curr_time,$old_time)
{
  return round($curr_time - $old_time ,2) * 1000 .'ms';
}

$max = 300000;
$str = '';
//new对象
$new_time = microtime(true);
for($i = 0; $i<= $max;$i++){
  $pro = new BarBookPrototype();
  $pro->setTitle($i);
  $pro->getTitle();
}
$str .= '创建对象使用时间:'. toMillisecond(microtime(true),$new_time).PHP_EOL;

//克隆
$clone_time = microtime(true);
$barBookPrototype = new BarBookPrototype();
for($i = 0; $i<= $max;$i++){
  $pro = clone $barBookPrototype;
  $pro->setTitle($i);
  $pro->getTitle();
}
$str .= '克隆对象使用时间:'. toMillisecond(microtime(true),$clone_time).PHP_EOL;

echo $str;
专心学习不瞎搞
讨论数量: 2

file

原型类__constrct()复杂时 clone会比new更节省开销

因为clone并不会执行__construct

4年前 评论

file

laravelUser模型为例, clonenew快很多

然后取消User模型的__construct

file

速度几乎一致

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!