Skip to content

Commit

Permalink
perf: Optimize ObjectCache & Context.
Browse files Browse the repository at this point in the history
  • Loading branch information
priyadi committed Jan 18, 2024
1 parent b8f8c3c commit f06e184
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 24 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
* perf(`ScalarToScalarTransformer`): Optimize.
* perf: Remove type guesser from `TypeResolver`.
* perf(`ObjectCache`): Optimize using plain arrays.
* perf: Optimize `ObjectCache` & `Context`.

## 0.5.14

Expand Down
2 changes: 1 addition & 1 deletion src/Context/Context.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,6 @@ public function without(object|string $value): self
public function get(string $class): object
{
// @phpstan-ignore-next-line
return $this->context[$class] ?? throw new ContextMemberNotFoundException($class);
return $this->context[$class] ?? throw new ContextMemberNotFoundException();
}
}
7 changes: 0 additions & 7 deletions src/Context/ContextMemberNotFoundException.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,4 @@

class ContextMemberNotFoundException extends RuntimeException
{
/**
* @param class-string $class
*/
public function __construct(string $class)
{
parent::__construct(sprintf('Cannot find object with class "%s" in context', $class));
}
}
23 changes: 7 additions & 16 deletions src/ObjectCache/ObjectCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,20 +84,6 @@ private function isPreCached(mixed $source, Type $targetType, Context $context):
return isset($this->preCache[$key][$targetTypeString]);
}

private function removePrecache(mixed $source, Type $targetType, Context $context): void
{
if (!is_object($source)) {
return;
}

$targetTypeString = $this->typeResolver->getTypeString($targetType);
$key = spl_object_id($source);

if (isset($this->preCache[$key][$targetTypeString])) {
unset($this->preCache[$key][$targetTypeString]);
}
}

public function containsTarget(mixed $source, Type $targetType, Context $context): bool
{
if (!is_object($source)) {
Expand Down Expand Up @@ -156,7 +142,7 @@ public function saveTarget(

if (
$addIfAlreadyExists === false
&& $this->containsTarget($source, $targetType, $context)
&& isset($this->cache[$key][$targetTypeString])
) {
throw new LogicException(sprintf(
'Target object for source object "%s" and target type "%s" already exists',
Expand All @@ -170,6 +156,11 @@ public function saveTarget(
}

$this->cache[$key][$targetTypeString] = $target;
$this->removePrecache($source, $targetType, $context);

// remove precache

if (isset($this->preCache[$key][$targetTypeString])) {
unset($this->preCache[$key][$targetTypeString]);
}
}
}

0 comments on commit f06e184

Please sign in to comment.