Skip to content

Commit

Permalink
Add castTypeCache
Browse files Browse the repository at this point in the history
getCastType is called a lot when processing models with defined casts and contributes to a significant number of overall calls.  Caching the results of the key conversion can result in significant performance improvement when processing large numbers of models.
  • Loading branch information
serpentblade committed Aug 4, 2022
1 parent c156e13 commit 424e8cf
Showing 1 changed file with 19 additions and 8 deletions.
27 changes: 19 additions & 8 deletions src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
Expand Up @@ -165,6 +165,13 @@ trait HasAttributes
*/
protected static $setAttributeMutatorCache = [];

/**
* The cache of the converted cast types.
*
* @var array
*/
protected static $castTypeCache = [];

/**
* The encrypter instance that is used to encrypt attributes.
*
Expand Down Expand Up @@ -818,19 +825,23 @@ protected function getEnumCastableAttributeValue($key, $value)
*/
protected function getCastType($key)
{
if ($this->isCustomDateTimeCast($this->getCasts()[$key])) {
return 'custom_datetime';
}
$castType = $this->getCasts()[$key];

if ($this->isImmutableCustomDateTimeCast($this->getCasts()[$key])) {
return 'immutable_custom_datetime';
if (isset(static::$castTypeCache[$castType])) {
return static::$castTypeCache[$castType];
}

if ($this->isDecimalCast($this->getCasts()[$key])) {
return 'decimal';
if ($this->isCustomDateTimeCast($castType)) {
$convertedCastType = 'custom_datetime';
} elseif ($this->isImmutableCustomDateTimeCast($castType)) {
$convertedCastType = 'immutable_custom_datetime';
} elseif ($this->isDecimalCast($castType)) {
$convertedCastType = 'decimal';
} else {
$convertedCastType = trim(strtolower($castType));
}

return trim(strtolower($this->getCasts()[$key]));
return static::$castTypeCache[$castType] = $convertedCastType;
}

/**
Expand Down

0 comments on commit 424e8cf

Please sign in to comment.