Facorazza
Facorazza

Reputation: 336

Is it faster to create a new class inside a function or pass it as a parameter in PHP

I've got a class that is used in a few functions independently from one another. So my question is: is it faster to pass the initiated class as a parameter to the function or to create a new instance every time the function is called upon?

Like this:

$class_a = new Class_a;

function rnd_fun($class_a){
... do stuff...
}

Or like this:

function rnd_fun(){
$class_a = new Class_a;
... do stuff...
unset($class_a);
}

Upvotes: 2

Views: 75

Answers (1)

Facorazza
Facorazza

Reputation: 336

I tried to do a benchmark and these are the results by using this very creative class

class Class_a {
    public $first_name = "";
    public $age = "";

    public function setVar($first_name, $age){
        $this->first_name = $first_name;
        $this->age = $age;
    }

    public function wasteTime(){
        $i = 0;
        while($i < 100){
            $this->age = $this->age * $i;
            $this->age = $this->age / pi();
            $i++;
        }
    }
}

By passing the class as a parameter I got something around 0.46s using this code:

$class_a = new Class_a;

$i = 0;
while($i < 10000){
    test($class_a);
    $i++;
}

function test($class_a){
        $class_a->setVar("Geronimo", "72.1");
        $class_a->wasteTime();
    }

This is by initiating a new class inside the function:

$i = 0;
while($i < 10000){
    test();
    $i++;
}

function test(){
    $class_a = new Class_a;
    $class_a->setVar("Geronimo", "72.1");
    $class_a->wasteTime();
    unset($class_a);
}

I have to point out though that the second method took a slightly higher time to execute (around 0.47s).

However I believe that the difference between the two is negligible since both run at around the same speed for this many iteration and their delay won't be noticeable in an average piece of code.

Upvotes: 2

Related Questions