Skip to content

Commit

Permalink
Optimize TypeRegistry::lookupName() from O(N) to O(1)
Browse files Browse the repository at this point in the history
  • Loading branch information
mvorisek committed Jul 1, 2023
1 parent ee7359a commit 611f495
Showing 1 changed file with 21 additions and 5 deletions.
26 changes: 21 additions & 5 deletions src/Types/TypeRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

use Doctrine\DBAL\Exception;

use function array_search;
use function spl_object_id;

/**
* The type registry is responsible for holding a map of all known DBAL types.
Expand All @@ -16,6 +16,8 @@ final class TypeRegistry
{
/** @var array<string, Type> Map of type names and their corresponding flyweight objects. */
private array $instances;
/** @var array<int, string>|null */
private ?array $instancesReverseIndex = null;

/** @param array<string, Type> $instances */
public function __construct(array $instances = [])
Expand Down Expand Up @@ -77,6 +79,9 @@ public function register(string $name, Type $type): void
}

$this->instances[$name] = $type;
if ($this->instancesReverseIndex !== null) {
$this->instancesReverseIndex[spl_object_id($type)] = $name;
}
}

/**
Expand All @@ -95,6 +100,9 @@ public function override(string $name, Type $type): void
}

$this->instances[$name] = $type;
if ($this->instancesReverseIndex !== null) {
$this->instancesReverseIndex[spl_object_id($type)] = $name;
}
}

/**
Expand All @@ -111,12 +119,20 @@ public function getMap(): array

private function findTypeName(Type $type): ?string
{
$name = array_search($type, $this->instances, true);
if ($this->instancesReverseIndex === null) {
$reverseIndex = [];
foreach ($this->instances as $name => $v) {
$reverseIndex[spl_object_id($v)] = $name;
}

if ($name === false) {
return null;
$this->instancesReverseIndex = $reverseIndex;
}

return $name;
$name = $this->instancesReverseIndex[spl_object_id($type)] ?? null;
if ($name !== null && $this->instances[$name] === $type) {
return $name;
}

return null;
}
}

0 comments on commit 611f495

Please sign in to comment.