Last active
October 20, 2017 15:27
-
-
Save skobkin/4e120409de177c4d5d4fe4cc82a092d0 to your computer and use it in GitHub Desktop.
Small hash caching benchmark
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 LazyCachedHash | |
{ | |
private $data = []; | |
private $dataHash = null; | |
public function __construct($data = array()) | |
{ | |
$this->data = $data; | |
} | |
public function getDataHash() | |
{ | |
if (null === $this->dataHash) { | |
$this->dataHash = md5(json_encode($this->data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); | |
} | |
return $this->dataHash; | |
} | |
} | |
class EagerCachedHash | |
{ | |
private $data = []; | |
private $dataHash = null; | |
public function __construct($data = array()) | |
{ | |
$this->data = $data; | |
$this->dataHash = md5(json_encode($this->data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); | |
} | |
public function getDataHash() | |
{ | |
return $this->dataHash; | |
} | |
} | |
class NonCachedHash | |
{ | |
private $data = []; | |
public function __construct($data = array()) | |
{ | |
$this->data = $data; | |
} | |
public function getDataHash() | |
{ | |
return md5(json_encode($this->data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); | |
} | |
} | |
$data = [ | |
'a' => 129841, | |
//'b' => str_repeat('asdfgl;sdjfg;lsdjglkdsfjhglkdsfhglksdhglsdkghsdl;kgjdslkfgjhnsd;fbjsdflkfgjhsdlkrgjhsdlkghjsdlgkjhdsglksdhglksdjhglsdkjhgfsdlkjgfhnsdlkgjhsdlkgjfdsfgsdfgsdgsdgfsdgf'.PHP_EOL, 100) | |
'b' => 'asdfgl;sdjfg;lsdjglkdsfjhglkdsfhglksdhglsdk' | |
]; | |
$lazyCachedStart = microtime(true); | |
for ($i = 0; $i < 100000; $i++) { | |
$object = new LazyCachedHash($data); | |
for ($j = 0; $j < 10; $j++) { | |
$hash = $object->getDataHash(); | |
} | |
} | |
$lazyCachedStop = microtime(true); | |
$eagerCachedStart = microtime(true); | |
for ($i = 0; $i < 100000; $i++) { | |
$object = new EagerCachedHash($data); | |
for ($j = 0; $j < 10; $j++) { | |
$hash = $object->getDataHash(); | |
} | |
} | |
$eagerCachedStop = microtime(true); | |
$nonCachedStart = microtime(true); | |
for ($i = 0; $i < 100000; $i++) { | |
$object = new NonCachedHash($data); | |
for ($j = 0; $j < 10; $j++) { | |
$hash = $object->getDataHash(); | |
} | |
} | |
$nonCachedStop = microtime(true); | |
var_dump(array( | |
'lazy' => ($lazyCachedStop - $lazyCachedStart), | |
'eager' => ($eagerCachedStop - $eagerCachedStart), | |
'non_cached' => ($nonCachedStop - $nonCachedStart) | |
)); |
Author
skobkin
commented
Oct 20, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment