skobkin
PHP
2017.10.20 18:17
Небольшой бенчмарк о смысле кеширования хэша.
<?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)
));