Home » Php » PHP – Execution Time Faster on indirect object creation

PHP – Execution Time Faster on indirect object creation

Posted by: admin October 26, 2017 Leave a comment

Questions:

I have 3 files with the following code:

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;

When I was running the above code this is much faster than I was creating an object directly using the following code:

require_once("TObj.php");

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

Shouldn’t this be the vice-versa? Or Am I checking the wrong way for analyzing the computation time? Please do mind my English as I’m not much of a speaker 🙁

I thought the latter will be faster but it was not the case when tested both on a server with 512 MB Ram and a single core ( Linux ) and also on a local system with 4GB RAM and 4 core(s) (windows)

What Am I doing wrong?

Answers:

Leave a Reply

Your email address will not be published. Required fields are marked *