From 786a7239d7e8c7e76e5e30a219cdfb0757e9dda0 Mon Sep 17 00:00:00 2001 From: Stephen Clouse Date: Mon, 24 Jul 2017 16:27:15 -0500 Subject: [PATCH] Add caching for unit lookups with getUnit() --- source/AbstractPhysicalQuantity.php | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/source/AbstractPhysicalQuantity.php b/source/AbstractPhysicalQuantity.php index 0d61bbf..029e332 100644 --- a/source/AbstractPhysicalQuantity.php +++ b/source/AbstractPhysicalQuantity.php @@ -12,6 +12,23 @@ abstract class AbstractPhysicalQuantity implements PhysicalQuantityInterface */ // protected static $unitDefinitions; + /** + * Static cache for unit lookups. + * + * @var UnitOfMeasureInterface[] + */ + private static $unitCache = []; + + /** + * Create a cache key for the unit lookup cache. + * + * @var UnitOfMeasureInterface[] + */ + private static function buildUnitCacheKey($unit) + { + return get_called_class() . '#' . $unit; + } + /** * Register a new unit of measure for all instances of this this physical quantity. * @@ -47,9 +64,14 @@ public static function getUnit($unit) static::initialize(); } + $key = static::buildUnitCacheKey($unit); + if (isset(self::$unitCache[$key])) { + return self::$unitCache[$key]; + } + foreach (static::$unitDefinitions as $unitOfMeasure) { if ($unit === $unitOfMeasure->getName() || $unitOfMeasure->isAliasOf($unit)) { - return $unitOfMeasure; + return self::$unitCache[$key] = $unitOfMeasure; } }