Home>Article>Backend Development> Performance comparison of clone and new in PHP (code example)
Clone and new should not be compared together. Their functions are different. But there may be some scenarios where clone or new can be used, so which one should we choose at this time?
I wrote two tests, the first is to declare an empty class, and the second is a class with constructors and attributes. In addition, I also added PHP serialization testing.
International practice, directly enter the code, it is clear at a glance.
Code
data = $data; } } function test2() { echo '带构造方法、属性的类:', PHP_EOL; $constructData = [ 'id' => 1, 'name' => 'imi 框架牛逼', 'description' => 'IMI 是一款基于 Swoole 开发的协程 PHP 开发框架,拥有常驻内存、协程异步非阻塞IO等优点。', 'url' => 'https://www.imiphp.com', ]; $a = new B($constructData); test('B clone', function() use($a){ for($i = 0; $i < TEST_COUNT; ++$i) { $obj = clone $a; } }); test('B new', function() use($a){ for($i = 0; $i < TEST_COUNT; ++$i) { $obj = new B($a->data); } }); $serialize = serialize($a); test('B unserialize', function() use($serialize){ for($i = 0; $i < TEST_COUNT; ++$i) { $obj = unserialize($serialize); } }); } test2();
Run result
Empty class:
A clone time: 0.0015249252319336s A new time: 0.00090503692626953s A unserialize time: 0.005108118057251s
Class with constructor and attributes:
B clone time: 0.00072503089904785s B new time: 0.0015559196472168s B unserialize time: 0.0084571838378906s
Conclusion
Judging from the test results of the empty class, new has higher performance.
Judging from the test results of classes with construction methods and attributes, the performance of clone is much higher than that of new with construction parameters.
Serialization performance is as worrisome as ever, so don’t use it if you can’t use it.
So, we should use clone where we should, and the performance is not bad.
The above is the detailed content of Performance comparison of clone and new in PHP (code example). For more information, please follow other related articles on the PHP Chinese website!