سؤال

My question sounds really simple but I wasn't able to find an answer on the Internet.

Let's assume you have a class having some attributes. Is there any performance difference between initialization of an empty object and changing the values of the variables later:

$obj = new MyClass();
$obj->value1 = 1;
$obj->value2 = 2;

and the creation of a constructor which basically does the same thing:

class MyClass
{
    public $value1;
    public $value2;

    public function __construct($val1, $val2)
    {
        $this->value1 = $val1;
        $this->value2 = $val2;
    }
}

$obj = new MyClass(1,2);

Please don't think about code readability and best practices :)

هل كانت مفيدة؟

المحلول

Only for fun I tried 1 000 000 iterations with this resultats:

in constructor

lukashes@biorobot:/tmp/php$ php in.php

string(13) "1012924.416kb"

string(18) "2.2154049873352sec"

out of constuctor

lukashes@biorobot:/tmp/php$ php out.php

string(12) "996933.632kb"

string(18) "2.0962958335876sec"

Note: I am save all 1 000 000 instances.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top