-
-
Save qRoC/326a90c0244fb87e9ea468ecbdcab4c8 to your computer and use it in GitHub Desktop.
Benchmark newInstanceWithoutConstructor vs unserialize for object creation vs json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
PHP 5.6.29: | |
ReflectionClass::newInstanceWithoutConstructor: 0.17457699775696 | |
ReflectionClass::newInstanceWithoutConstructor(json): 0.11926913261414 | |
unserialize: 0.21122980117798 | |
PHP 7.1.0: | |
ReflectionClass::newInstanceWithoutConstructor: 0.066795110702515 | |
ReflectionClass::newInstanceWithoutConstructor(json): 0.065139055252075 | |
unserialize: 0.10229301452637 | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Foo implements \Serializable | |
{ | |
protected $a; | |
protected $b; | |
public function __construct($a, $b) | |
{ | |
$this->a = $a; | |
$this->b = $b; | |
} | |
public function serialize() | |
{ | |
return serialize([$this->a, $this->b]); | |
} | |
public function unserialize($data) | |
{ | |
list($this->a, $this->b) = unserialize($data); | |
} | |
} | |
class FooSub extends Foo | |
{ | |
} | |
class FooJson extends Foo | |
{ | |
public function serialize() | |
{ | |
return json_encode([$this->a, $this->b]); | |
} | |
public function unserialize($data) | |
{ | |
list($this->a, $this->b) = json_decode($data, true); | |
} | |
} | |
$fooObj = new FooSub(123.4, 'Hello'); | |
$serializeObjStr = serialize($fooObj); | |
$serializeDataStr = $fooObj->serialize(); | |
$fooJsonObj = new FooJson(123.4, 'Hello'); | |
$serializeJsonDataStr = $fooJsonObj->serialize(); | |
echo 'ReflectionClass::newInstanceWithoutConstructor: '; | |
$r = new ReflectionClass(FooSub::class); | |
$start = microtime(true); | |
for ($i = 1; $i < 100000; $i++) { | |
$obj = $r->newInstanceWithoutConstructor(); | |
$obj->unserialize($serializeDataStr); | |
} | |
$now = microtime(true); | |
echo ($now - $start) . PHP_EOL; | |
echo 'ReflectionClass::newInstanceWithoutConstructor(json): '; | |
$r = new ReflectionClass(FooJson::class); | |
$start = microtime(true); | |
for ($i = 1; $i < 100000; $i++) { | |
$obj = $r->newInstanceWithoutConstructor(); | |
$obj->unserialize($serializeJsonDataStr); | |
} | |
$now = microtime(true); | |
echo ($now - $start) . PHP_EOL; | |
echo 'unserialize: '; | |
$start = microtime(true); | |
for ($i = 1; $i < 100000; $i++) { | |
$obj = unserialize($serializeObjStr); | |
} | |
$now = microtime(true); | |
echo ($now - $start) . PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment