From 8f7f4610cba02fe896a801edc11b7c0e39e4c948 Mon Sep 17 00:00:00 2001 From: Tim Otten Date: Wed, 23 Jan 2019 12:52:58 -0800 Subject: [PATCH] NaiveHasTrait - Reduce roundtrips in `has()` The `NaiveHasTrait` is a generic implementation of PSR-16 `has()` which builds on the logic of PSR-16 `get()`. This reduces I/O for `has()`. Before ------ * Each call to `has()` triggers two calls to `get()`. After ----- * Each call to `has()` triggers one call to `get()`. Comments -------- The correctness of this stems from the uniqueness of the `$nack` value. To wit: if you always use the same constant (e.g. `NULL` or `0` or `''` or `'no-value'`) to signify a cache-miss, then it's trivial to produce a collision/incorrect-result. (Simply store that constant.) But if the value is a sufficiently unique nonce, then it becomes impractical to produce a collision/incorrect-result. --- CRM/Utils/Cache/NaiveHasTrait.php | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/CRM/Utils/Cache/NaiveHasTrait.php b/CRM/Utils/Cache/NaiveHasTrait.php index 4c270b2bd9..3a8260e7af 100644 --- a/CRM/Utils/Cache/NaiveHasTrait.php +++ b/CRM/Utils/Cache/NaiveHasTrait.php @@ -33,17 +33,14 @@ * The traditional CRM_Utils_Cache_Interface did not support has(). * To get drop-in compliance with PSR-16, we use a naive adapter. * - * Ideally, these should be replaced with more performant/native versions. + * There may be opportunities to replace/optimize in specific drivers. */ trait CRM_Utils_Cache_NaiveHasTrait { public function has($key) { - // This is crazy-talk. If you've got an environment setup where you might - // be investigating this, fix your preferred cache driver by - // replacing `NaiveHasTrait` with a decent function. - $hasDefaultA = ($this->get($key, NULL) === NULL); - $hasDefaultB = ($this->get($key, 123) === 123); - return !($hasDefaultA && $hasDefaultB); + $nack = CRM_Utils_Cache::nack() . 'ht'; + $value = $this->get($key, $nack); + return ($value !== $nack); } } -- 2.25.1