Skip to content

Optimize singleton resolution with early cache return #169

Merged
lesnik512 merged 5 commits intomainfrom
perf/early-cache-return
May 1, 2026
Merged

Optimize singleton resolution with early cache return #169
lesnik512 merged 5 commits intomainfrom
perf/early-cache-return

Conversation

@lesnik512
Copy link
Copy Markdown
Member

Summary

  • Short-circuit Factory.resolve() before kwargs compilation when cached instance exists — eliminates dict copy + recursive dependency resolution on every singleton hit (~4.5× faster)
  • Remove typing.cast from hot resolve paths — each was a no-op function call adding ~25-30ns
  • Single-pass kwargs split in _ensure_kwargs_cached — replaces two dict comprehensions with one loop

lesnik512 added 5 commits May 1, 2026 09:03
Move the cache-hit check before kwargs resolution in Factory.resolve()
so singleton providers return immediately without copying static_kwargs
or recursively resolving dependency providers on every call.
Replace dict.setdefault (which eagerly evaluates its default argument,
constructing a CacheItem on every call even for cache hits) with a
get-then-set pattern that only creates a CacheItem on first access.
setdefault is atomic in CPython, which prevents a race where two
threads could each create a CacheItem and one overwrites the other,
losing cached instances. The throwaway construction cost is the price
of thread safety.
typing.cast is a no-op function call at runtime that still costs
~25-30ns per invocation. Remove it from resolve_provider and
Factory.resolve where it runs on every resolution.
Replace two dict comprehensions (one filtering providers, one filtering
statics) with a single loop that partitions into both dicts in one pass.
@lesnik512 lesnik512 self-assigned this May 1, 2026
@lesnik512 lesnik512 merged commit bfec7d9 into main May 1, 2026
7 checks passed
@lesnik512 lesnik512 deleted the perf/early-cache-return branch May 1, 2026 06:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant