Skip to content

Instantly share code, notes, and snippets.

@skobkin
Last active October 20, 2017 15:27
Show Gist options
  • Save skobkin/4e120409de177c4d5d4fe4cc82a092d0 to your computer and use it in GitHub Desktop.
Save skobkin/4e120409de177c4d5d4fe4cc82a092d0 to your computer and use it in GitHub Desktop.
Small hash caching benchmark
<?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)
));
@skobkin
Copy link
Author

skobkin commented Oct 20, 2017

> $ php7.2 CachedHash.php
array(3) {
  ["lazy"]=>
  float(0.10670709609985)
  ["eager"]=>
  float(0.096924066543579)
  ["non_cached"]=>
  float(0.52893090248108)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment