Memoization
Also Known As
memoize
function memoization
result caching
TL;DR
Caching the result of a pure function call keyed by its arguments so repeated calls with the same inputs return immediately.
Explanation
Memoization is an optimisation for pure (or effectively pure) functions where the same inputs always produce the same output. The first call computes the result and stores it in a lookup table; subsequent calls with the same arguments return the cached result instantly. In PHP, this is commonly implemented with a local static array or instance property. It is most valuable for recursive computations (Fibonacci, tree traversals), repeated regex compilations, or expensive lookups (translations, configuration values) called multiple times per request.
Common Misconception
✗ Memoization and caching are the same thing. Memoization is function-level — it caches the return value of a pure function keyed on its arguments, within a single execution context. General caching is broader, persists across requests, and applies to any data, not just function outputs.
Why It Matters
Memoization caches the result of a pure function call indexed by its arguments — calling an expensive function with the same input twice costs only one execution; subsequent calls return the cached result.
Common Mistakes
- Memoizing functions with side effects — the cached result bypasses the side effect on repeat calls.
- Not including all deterministic inputs in the cache key — different inputs produce the same key, returning wrong results.
- Unbounded memoization caches — memory grows indefinitely for functions called with many unique inputs.
- Memoizing across requests via static properties without TTL — stale results persist for the process lifetime.
Code Examples
✗ Vulnerable
function expensiveCalc(int $n): int {
return // ... heavy computation each call
}
✓ Fixed
function expensiveCalc(int $n): int {
static $cache = [];
return $cache[$n] ??= /* heavy computation */;
}
References
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
15 Mar 2026
Edited
22 Mar 2026
Views
37
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 2
Ahrefs 1
Amazonbot 1
No pings yesterday
Ahrefs 9
Amazonbot 8
Perplexity 7
Unknown AI 2
Google 2
SEMrush 2
Bing 1
How they use it
crawler 30
crawler_json 1
Related categories
⚡
DEV INTEL
Tools & Severity
🟡 Medium
⚙ Fix effort: Low
⚡ Quick Fix
Cache a function's return value in a static variable keyed by its arguments — PHP's static variables persist for the request lifetime, giving O(1) repeat calls with zero serialisation
📦 Applies To
any
web
cli
queue-worker
🔗 Prerequisites
🔍 Detection Hints
Expensive pure function called multiple times with same arguments within a request; recursive function with overlapping subproblems and no cache
Auto-detectable:
✗ No
blackfire
xdebug
⚠ Related Problems
🤖 AI Agent
Confidence: Medium
False Positives: Medium
✗ Manual fix
Fix: Medium
Context: Function
Tests: Update