From 89efb49b20c652e23fcc5d386d7dd1276d21a708 Mon Sep 17 00:00:00 2001 From: loks0n <22452787+loks0n@users.noreply.github.com> Date: Fri, 17 Apr 2026 13:56:48 +0100 Subject: [PATCH] perf: replace str_replace with substr + cache in getPermissionsByType Eliminates repeated str_replace calls (294K+ per profiling run) by using str_starts_with + substr on the predictable type("role") format, and caches results per Document instance. Cache is invalidated on setAttribute('$permissions'). Co-Authored-By: Claude Sonnet 4.6 --- src/Database/Document.php | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/src/Database/Document.php b/src/Database/Document.php index d50a957ca..6a0449bdf 100644 --- a/src/Database/Document.php +++ b/src/Database/Document.php @@ -15,6 +15,9 @@ class Document extends ArrayObject public const SET_TYPE_PREPEND = 'prepend'; public const SET_TYPE_APPEND = 'append'; + /** @var array> */ + private array $permissionCache = []; + /** * Construct. * @@ -144,16 +147,21 @@ public function getWrite(): array */ public function getPermissionsByType(string $type): array { - $typePermissions = []; + if (isset($this->permissionCache[$type])) { + return $this->permissionCache[$type]; + } + + $prefix = $type . '("'; + $prefixLen = \strlen($prefix); + $result = []; foreach ($this->getPermissions() as $permission) { - if (!\str_starts_with($permission, $type)) { - continue; + if (\str_starts_with($permission, $prefix)) { + $result[] = \substr($permission, $prefixLen, -2); } - $typePermissions[] = \str_replace([$type . '(', ')', '"', ' '], '', $permission); } - return \array_unique($typePermissions); + return $this->permissionCache[$type] = \array_unique($result); } /** @@ -243,6 +251,10 @@ public function getAttribute(string $name, mixed $default = null): mixed */ public function setAttribute(string $key, mixed $value, string $type = self::SET_TYPE_ASSIGN): static { + if ($key === '$permissions') { + $this->permissionCache = []; + } + switch ($type) { case self::SET_TYPE_ASSIGN: $this[$key] = $value;