Skip to content

Commit

Permalink
Merge pull request #72 from noaa-nws-nids/master
Browse files Browse the repository at this point in the history
Add caching for unit lookups with getUnit()
  • Loading branch information
triplepoint authored Jul 26, 2017
2 parents bcd9071 + 786a723 commit cdbfa00
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion source/AbstractPhysicalQuantity.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -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;
}
}

Expand Down

0 comments on commit cdbfa00

Please sign in to comment.