Skip to content

Commit cdaaa9e

Browse files
lan17claude
andcommitted
perf: cache urn and prefix in GCacheKey constructor
Compute urn and prefix once during __post_init__ instead of on every property access. URN access is now 16x faster (0.029 µs vs 0.47 µs). Trade-off: creation is slightly slower (+0.59 µs) but breaks even after just 2 URN accesses per key, which is typical for cache operations. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
1 parent 914e3af commit cdaaa9e

1 file changed

Lines changed: 19 additions & 23 deletions

File tree

src/gcache/config.py

Lines changed: 19 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,24 @@ class GCacheKey:
125125
invalidation_tracking: bool = False
126126
default_config: GCacheKeyConfig | None = None
127127
serializer: Serializer | None = None
128+
# Cached computed fields (set in __post_init__)
129+
prefix: str = field(init=False)
130+
urn: str = field(init=False)
131+
132+
def __post_init__(self) -> None:
133+
# Compute prefix
134+
prefix = f"{self.key_type}:{self.id}"
135+
if _GLOBAL_GCACHE_STATE.urn_prefix:
136+
prefix = f"{_GLOBAL_GCACHE_STATE.urn_prefix}:{prefix}"
137+
if self.invalidation_tracking:
138+
prefix = "{" + prefix + "}"
139+
object.__setattr__(self, "prefix", prefix)
140+
141+
# Compute urn
142+
args_str = ""
143+
if self.args:
144+
args_str = "?" + "&".join([f"{arg[0]}={arg[1]}" for arg in self.args])
145+
object.__setattr__(self, "urn", f"{prefix}{args_str}#{self.use_case}")
128146

129147
def __hash__(self) -> int:
130148
# Tuple hashing is fast (C implementation) and avoids string allocation
@@ -141,30 +159,8 @@ def __eq__(self, other: object) -> bool:
141159
and self.args == other.args
142160
)
143161

144-
def _args_to_str(self) -> str:
145-
if self.args:
146-
joined = "&".join([f"{arg[0]}={arg[1]}" for arg in self.args])
147-
return "?" + joined
148-
return ""
149-
150-
@property
151-
def prefix(self) -> str:
152-
prefix = f"{self.key_type}:{self.id}"
153-
if _GLOBAL_GCACHE_STATE.urn_prefix:
154-
prefix = f"{_GLOBAL_GCACHE_STATE.urn_prefix}:{prefix}"
155-
if self.invalidation_tracking:
156-
prefix = "{" + prefix + "}"
157-
return prefix
158-
159-
def _get_str(self) -> str:
160-
return f"{self.prefix}{self._args_to_str()}#{self.use_case}"
161-
162162
def __str__(self) -> str:
163-
return self._get_str()
164-
165-
@property
166-
def urn(self) -> str:
167-
return self._get_str()
163+
return self.urn
168164

169165

170166
# Get cache config given a use case.

0 commit comments

Comments
 (0)