PHP - 间接对象创建的执行时间更快

时间:2017-10-25 12:13:54

标签: php performance performance-testing

我有3个文件,包含以下代码:

Filename: TCObj.php

class TCObj {
    protected $objects;

    public function __construct(){
        $this->objects = array();
    }

    public function register_service($service) {
        if(!isset($this->objects[$service])) {
            $this->objects[$service] = new $service;
        }
        return $this->objects[$service];            
    }       
}

File Name: TObj.php

class TObj {
    public function __construct(){

    }

    public function hello() {
        echo "Hello!!!";
    }
}


test.php contains the following code: 

require_once("TCObj.php");  
require_once("TObj.php");

$start_time = microtime(true);
$o = new TCObj();
$p = $o->register_service("TObj");
$p->hello();
$end_time = microtime(true);
echo "<br />";
echo $end_time - $start_time;

当我运行上面的代码时,这比我使用以下代码直接创建对象要快得多:

require_once("TObj.php");

$start_time = microtime(true);
$p = new TObj();    
$p->hello();
$end_time = microtime(true);
echo "<br />";
echo $end_time - $start_time;

这不应该反之亦然吗?或者我是否在检查分析计算时间的错误方法?请注意我的英语,因为我不是一个发言者:(

我认为后者会更快但是在具有512 MB Ram和单核(Linux)的服务器上以及在具有4GB RAM和4核(Windows)的本地系统上进行测试时情况并非如此)

我做错了什么?

0 个答案:

没有答案