dtcu5885 2019-01-27 08:24
浏览 69

PHP中构造函数的类较慢

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 "
";    

$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.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 SQL Server下载
    • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
    • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
    • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
    • ¥15 python爬取bilibili校园招聘网站
    • ¥30 求解达问题(有红包)
    • ¥15 请解包一个pak文件
    • ¥15 不同系统编译兼容问题
    • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
    • ¥30 数字电源对DSP芯片的具体要求