I have created two classes:
class TestClass
{
public $id;
public $name;
public $time;
}
class TestClassCtor
{
public $id;
public $name;
public $time;
public function __construct()
{
}
}
Now I run a simple code:
$tt = microtime(true);
$data = array();
for ($i = 0; $i < 10000; $i++)
{
$t = new TestClass();
$t->id = rand();
$t->name = rand();
$t->time = rand();
$data[] = $t;
}
echo microtime(true) - $tt;
echo "\n";
$tt = microtime(true);
$data1 = array();
for ($i = 0; $i < 10000; $i++)
{
$t = new TestClassCtor();
$t->id = rand();
$t->name = rand();
$t->time = rand();
$data1[] = $t;
}
echo microtime(true) - $tt;
Now, the second code with TestClassCtor
is around 30% slower. Why? (tested with PHP 5.6 and 7.1).
Edit:
The similar difference can be spotted with (in this case, I can understand it - passing arguments to method may be slower).
class TestClassCtorFill
{
public $id;
public $name;
public $time;
public function __construct($id, $name, $time)
{
$this->id = $id;
$this->name = $name;
$this->time = $time;
}
}
In this case, I can create class in one line as
for ($i = 0; $i < 10000; $i++)
{
$data1[] = new TestClassCtorFill(rand(), rand(), rand());
}
Yes, this is safer, because user must set all three parameters and he wont forget to set something.
However, when I use this inside my internal framework class, I can omit the ctor entirely and set members directly as with TestClass
to save some time. For a few instances, this wont be a much of a difference. But if I create tousands of them, it could be.
Edit 2
I know about cost of a function call. However, constructor is called upon new
, so if I write or not one, some constructor should be called. If there is no constructor provided by user a default one is caled. Memory for object must be allocated either way.