Skip to content

Commit

Permalink
fix: Change ObjectCache to use WeakMap. Should improve memory usage.
Browse files Browse the repository at this point in the history
  • Loading branch information
priyadi committed Jan 12, 2024
1 parent 391beba commit 7f7657c
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
* revert: Revert support for `Generator` target type. Impossible to have a
`Countable` result.
* docs: Improve documentation
* fix: Change `ObjectCache` to use `WeakMap`. Should improve memory usage.

## 0.5.3

Expand Down
18 changes: 10 additions & 8 deletions src/ObjectCache/ObjectCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,20 +23,22 @@
final class ObjectCache
{
/**
* @var \SplObjectStorage<object,\ArrayObject<string,object>>
* @var \WeakMap<object,\ArrayObject<string,object>>
*/
private \SplObjectStorage $cache;
private \WeakMap $cache;

/**
* @var \SplObjectStorage<object,\ArrayObject<string,true>>
* @var \WeakMap<object,\ArrayObject<string,true>>
*/
private \SplObjectStorage $preCache;
private \WeakMap $preCache;

public function __construct(
private TypeResolverInterface $typeResolver
) {
$this->cache = new \SplObjectStorage();
$this->preCache = new \SplObjectStorage();
/** @psalm-suppress MixedPropertyTypeCoercion */
$this->cache = new \WeakMap();
/** @psalm-suppress MixedPropertyTypeCoercion */
$this->preCache = new \WeakMap();
}

private function isBlacklisted(mixed $source): bool
Expand Down Expand Up @@ -81,7 +83,7 @@ public function preCache(mixed $source, Type $targetType): void
$this->preCache[$source] = $arrayObject;
}

$this->preCache->offsetGet($source)->offsetSet($targetTypeString, true);
$this->preCache->offsetGet($source)?->offsetSet($targetTypeString, true);
}

private function isPreCached(mixed $source, Type $targetType): bool
Expand Down Expand Up @@ -181,7 +183,7 @@ public function saveTarget(
$this->cache[$source] = $arrayObject;
}

$this->cache->offsetGet($source)->offsetSet($targetTypeString, $target);
$this->cache->offsetGet($source)?->offsetSet($targetTypeString, $target);
$this->removePrecache($source, $targetType);
}
}

0 comments on commit 7f7657c

Please sign in to comment.