Abandoning DRY on the Hot Path: Significantly Cutting Millions of Function Calls
When I first wrote TypePHP (v0.1 through v0.10), I did what every "good" senior PHP developer is supposed to do. Clean abstractions. Strict DRY. Textbook SOLID. 'Polite little polymorphic interfaces everywhere you looked..'
Every type check walked politely through TypeValidatorRegistry, hopped into a strategy class like IdentifierValidator or ArrayShapeValidator, formatted nice context strings along the way, and shared configuration helpers across files like a well-behaved citizen.
It looked gorgoeus in the IDE. Absolute art. And then you actually ran it inside tight loops or generic-heavy collection suites and it moved like it was wading through wet cement wearing concrete shoes.
A 6,928-test generics stress suite (noctud/collection) took 2 minutes and 19 seconds sequentially. Native PHP did the same work in 6.5 seconds. Validating a 100,000-element list<int> 2,000 times took 21.7 seconds without JIT. I stared at those numbers and felt personnally attacked.
This is the story of the uncomfortable realization that followed: what makes cold business logic clean is often pure poison for a runtime engine. By splitting TypePHP into clean cold paths and mechanically sympathetic hot paths, the numbers got a lot less embarassing:
Many thanks to delacry for
noctud/collection, the library this analysis is based on. I also contributed back with PR #64, which fixes type violations that PHPStan missed and TypePHP surfaced. Along the way, the process exposed several false positives on TypePHP's side, which have since been fixed.
- 118.0M → 12.0M function calls (9.8× fewer calls) under
php-spxonMutableHashMapTest. - 5.44× faster sequentially (2m 19s → 25.6s) and 8.18× faster in parallel (1m 10s → 8.61s) on
noctud/collection's 6,928 tests (hybrid mode). - Up to 30.1× faster on collection and shape benchmarks on PHP 8.5.12 (full mode), hitting 3.53M ops/sec under Tracing JIT.
- ~1.2% overhead (+0.66s over 54.46s) on a real-world 430-test Laravel application (full mode).
Not bad for a pure-PHP type checker that people keep saying "will never be fast enough."
1. The Hidden Cost of "Clean Code" in Userland PHP
Most PHP packages never feel the weight of OOP dispatch because they hide behind database queries, HTTP calls, or framework boot cycles. TypePHP does not get that luxury. Its runtime checker sits on every function entry, every return statement, every generator yield, and every typed property write. It is the anoying friend who shows up to every single party.
When I ran php-spx against MutableHashMapTest (428 tests, 1,049 assertions, 1.9 milion property-dimension writes), the flat profile lit up bright red and yellow. The exact cost of clean abstractions inside tight loops was right there, staring back at me:
- Per-write reflection and template substitution: Every
$this->buckets[$k] = $vwrite went throughRuntimeTypeChecker::checkPropertyMemberAssign()(27.31s inc) →MemberAssignChecker::checkProperty()(24.37s inc) →validatePropertyElementMutation()(20.19s inc) →readPropertyValue()(1.78s inc). That triggered 11.6M calls toTemplateSubstitutor::substituteNode()(9.75s inc), 1.9M calls toDocblockParser::parseProperty(), and 1.9M calls togetReflectionProperty(). Beautifull architecture. Terrible runtime. - Repeated config lookups on hot paths:
Config::isInlinePropertiesEnabled()fired 3.8M times (393.0ms) andConfig::isArrayValidationHybrid()fired 1.9M times (249.0ms) inside a single test file. Because of course I needed to ask the same question millions of times. - Per-element polymorphic dispatch and eager string formatting: Validating collections element-by-element through
TypeValidatorRegistrywhile building context strings on the happy path turned tight loops into millions of throwaway frames and allocations. The kind of thing that looks "clean" until you look at the profilier and want to cry a little.
Total function calls for MutableHashMapTest alone hit 118.0 million (34.13s under SPX). One hundred and eighteen milion. For one test file. I still think about that number sometimes when I try to sleep.
Before: php-spx Flat Profile (118.0M Calls, 34.13s) on a specific test file (MutableHashMapTest)

2. Clean Outside, Inlined Inside: What Changed Across Three Eras
Instead of forcing one coding style across the whole repository (the classic senior-dev mistake), I split TypePHP like a compiler and VM:
- Cold Paths (Compile-Time AST Weaving, DocBlock Parsing, CLI, Reporting): Kept modular, DRY, and strictly SOLID (
ContractVisitor,EliminationSafetyPolicy,DocblockParser,SpecialTypeResolver,ViolationCollector). This code runs once per file or once per method signature. You can still be proud of it. - Hot Paths (Runtime Checking & Validation): Flattened into precompiled monomorphic plans,
WeakMapcaches, local opcode switches, and tight inline loops (RuntimeTypeChecker,MemberAssignChecker,GeneratorChecker,CollectionElementValidator,ArrayShapeValidator,GenericValidator). No more polite interfaces. Just work.
Here are the three biggest changes that turned that 118.0M-call SPX profile from a crime scene into something almost respectable.
1. Tight Inline Element Loops (CollectionElementValidator)
In v0.11–v0.14.0, instead of dispatching TypeValidatorRegistry::validate() for every single element of list<int> or string[], GenericValidator caches the element plan in a \WeakMap and hands primitive arrays to tight inline loops in CollectionElementValidator:
foreach ($items as $k => $v) {
if (! \is_int($v)) {
return ErrorFactory::createError(
$context . self::formatKey($k, $isList) . ' must be of type int, ' . TypeFormatter::formatGivenValue($v, $isSensitive) . ' given'
);
}
}Zero child method calls. Zero string concatenations unless an error is actually thrown. That single change cut the 100k-item list<int> benchmark from 21.7 seconds down to 878 ms. A 24.7× drop overnight. I may or may not have stared at the terminal for a full minute.
2. Precompiled Monomorphic Plans, \WeakMap Caches & Static Flags
In v0.14.1+, I stopped re-interpreting PHPDoc ASTs at function, shape, and property-write boundaries like some kind of interpretive dance:
RuntimeTypeCheckerExecution Plans: First-time execution compiles simple parameter contracts ($simpleScopePlanCache), return contracts ($simpleReturnPlanCache), generic constructors ($simpleCtorTemplatePlanCache),class-string<T>methods ($simpleClassStringTemplatePlanCache), and generic iterables ($simpleGenericIterablePlanCache) into flat integer opcode arrays.- Packed Property-Dim Fast Contracts (
$fastObjectContractCache):RuntimeTypeChecker::checkPropertyDimAssign()validates 1-level$this->items[$k] = $vwrites in O(1) via packed opcode tuples cached per object in a\WeakMap. It completely bypassesDocblockParser::parseProperty(),getReflectionProperty(),readPropertyValue(), andTemplateSubstitutor::substituteNode(). The old path was dramatic. The new one is boring and fast. WeakMapValidator Plans & Static Flags:ArrayShapeValidator,GenericValidator, andUnionValidatorcompileTypeNodeASTs once in\WeakMaps, whileConfig::syncFlags()keepsRuntimeTypeChecker::$isEnabled,$inlinePropertiesEnabled, and$arrayValidationHybridas plain static booleans. That eliminated all 5.7MConfig::is*()calls. Turns out asking the same question millions of times was not a great idea.
3. Compile-Time AST Elimination (v0.12 → v0.14)
The fastets runtime check is the one that never runs at all. When AST analysis proves a contract is already satisfied at compile time (literals, folded arithmetic, ternary confluence, $this identity returns, unmutated trusted parameters, safe unset($map['k']), or native PHP parameter types that already subsume the PHPDoc contract), TypePHP just leaves the raw PHP opcodes alone. No check. No overhead. Beautifull.
After: php-spx Flat Profile (12.0M Calls, 9.12s)
Look what happened to the exact same MutableHashMapTest run under php-spx:
- Total function calls dropped from 118.0M → 12.0M (9.8× fewer calls, −89.8%).
- Total SPX wall time dropped from 34.13s → 9.12s (3.74× faster even with full profiler overhead).
TemplateSubstitutor::substituteNode(11.6M calls),parseProperty,readPropertyValue,getReflectionProperty, andConfig::is*()all disappeared completely from the top 30. Gone. Like they never existed.- All 1.9M property-dimension writes now finish in 1.02s inside
checkPropertyDimAssign(), leavingNoctud\Collection\KeyHasher::hashMapKey()right behind it at #2. Finally some dignity.

3. Three Eras Compared: Same Machine, Same PHP 8.5.12
To make sure these gains were real and not just "works on my machine" theater, I ran the exact same 6-scenario benchmark script (GitHub Gist) across all three eras of TypePHP on the same PHP 8.5.12 machine. Median of 3 runs per scenario, 'array_validation' => 'full', confirmed runtime instrumentation. No funny business.
Standard PHP (No JIT)
| Scenario (Full Mode) | v0.1–v0.10 | v0.11–v0.14.0 | v0.14.1+ (Now) | Total Speedup |
|---|---|---|---|---|
Small list<int> (30 items, 10k calls) | 54.1 ms (185k ops/s) | 18.9 ms (528k ops/s) | 6.03 ms (1.66M ops/s) | 9.0× faster |
Large list<int> (1,000 items, 10k calls) | 1,218 ms (8.2k ops/s) | 60.0 ms (167k ops/s) | 51.6 ms (194k ops/s) | 23.6× faster |
Massive list<int> (100k items, 2k calls) | 21,724 ms (~21.7s) | 878 ms (2.3k ops/s) | 850 ms (2.4k ops/s) | 25.6× faster |
| Array Shapes (3 keys, 10k calls) | 19.8 ms (504k ops/s) | 21.3 ms (470k ops/s) | 5.07 ms (1.97M ops/s) | 3.9× faster |
| Unsealed Shapes (4 keys, 10k calls) | 25.2 ms (397k ops/s) | 26.3 ms (380k ops/s) | 8.04 ms (1.24M ops/s) | 3.1× faster |
Generic Map array<K, V> (50 items, 5k calls) | 64.5 ms (78k ops/s) | 55.8 ms (90k ops/s) | 9.64 ms (519k ops/s) | 6.7× faster |
With Tracing JIT (opcache.jit=tracing / 1254, 128M)
| Scenario (Full Mode) | v0.1–v0.10 | v0.11–v0.14.0 | v0.14.1+ (Now) | Total Speedup |
|---|---|---|---|---|
Small list<int> (30 items, 10k calls) | 25.4 ms (393k ops/s) | 11.0 ms (910k ops/s) | 3.39 ms (2.95M ops/s) | 7.5× faster |
Large list<int> (1,000 items, 10k calls) | 475 ms (21k ops/s) | 25.0 ms (399k ops/s) | 18.7 ms (534k ops/s) | 25.4× faster |
Massive list<int> (100k items, 2k calls) | 9,377 ms (213 ops/s) | 307 ms (6.5k ops/s) | 312 ms (6.4k ops/s) | 30.1× faster |
| Array Shapes (3 keys, 10k calls) | 12.1 ms (828k ops/s) | 12.7 ms (785k ops/s) | 2.83 ms (3.53M ops/s) | 4.3× faster |
| Unsealed Shapes (4 keys, 10k calls) | 17.3 ms (577k ops/s) | 15.8 ms (633k ops/s) | 3.91 ms (2.56M ops/s) | 4.4× faster |
Generic Map array<K, V> (50 items, 5k calls) | 36.3 ms (138k ops/s) | 27.0 ms (186k ops/s) | 3.22 ms (1.55M ops/s) | 11.3× faster |
The two waves show up pretty clearly:
- In
v0.11–v0.14.0,CollectionElementValidatorabsolutely crushedlist<int>(21.7s → 878 ms). Array Shapes (21.3 ms) and Generic Maps (55.8 ms) barely moved because they were still walking ASTs on every call. Classic. - In
v0.14.1+, precompiled plans and inlined fast paths dropped Array Shapes 4.2× (21.3 ms → 5.07 ms) and Generic Maps 5.8× without JIT (55.8 ms → 9.64 ms) and 8.4× with JIT (27.0 ms → 3.22 ms). Finally the shapes caught up.
4. Real-World Codebases: Pure-CPU Stress vs. Everyday Laravel
Microbenchmarks are fun and make for nice tables, but real applications are what actually matter. I measured TypePHP on two very different ends of the spectrum.
A. Worst-Case Pure-CPU Generics (noctud/collection)
noctud/collection is the ultimate stress test for a pure-PHP runtime type checker. 6,928 tests and 12,510 assertions, almost zero I/O, packed wall-to-wall with @template inference, variance enforcement, \WeakMap reified generics, conditional return types, fluent self<T> chains, iterables, and closures.
If TypePHP's hot path has a bottleneck anywhere, this suite will find it and laugh at you.
Validation Strategy Note
The noctud/collection runs below used 'array_validation' => 'hybrid' (Beartype-style O(1) boundary + random sampling for arrays over 128 items, plus O(1) element checks on property-dimension writes). That is why RuntimeTypeChecker::checkPropertyDimAssign() was able to validate all 1.9M writes in 1.02s.
| Mode | Native PHP (TYPEPHP_DISABLE=true) | Before (Early TypePHP) | After (TypePHP Now) | Wall-Time Speedup | Overhead Eliminated |
|---|---|---|---|---|---|
Sequential (phpunit) | 00:06.554 (82 MB) | 02:19.481 (112 MB) | 00:25.618 (130 MB) | 5.44× faster | −85.7% (132.9s → 19.1s) |
Parallel (paratest -p4) | 00:02.001 (62 MB) | 01:10.483 (62 MB) | 00:08.613 (62 MB) | 8.18× faster | −90.3% (68.5s → 6.6s) |
Sequential (phpunit): 02:19.481 → 00:25.618 (5.44× Faster)
Running all 6,928 tests in a single PHP process dropped from 2 minutes 19 seconds down to 25.6 seconds. That eliminated 85.7% of TypePHP's sequential runtime overhead. Still not native, but a lot less painful to watch.
Before (02:19.481, 112.00 MB):

After (00:25.618, 130.00 MB):

Parallel (paratest -p4): 01:10.483 → 00:08.613 (8.18× Faster)
Across 4 parallel workers, the entire 6,928-test generics suite dropped from 1 minute 10 seconds down to 8.61 seconds, keeping memory flat at 62.00 MB and eliminating 90.3% of TypePHP's overhead (adding just 6.6 seconds over raw native PHP). That one felt good.
Before (01:10.483, 62.00 MB):

After (00:08.613, 62.00 MB):

B. Typical I/O-Bound Web App (Real-World PHP Application)
Next I ran TypePHP on a real-world Laravel application (430 tests, 2,652 assertions, 216 instrumented application files) via php artisan test --compact with a warm cache. Unlike the pure-CPU stress run above, this Laravel suite used strict 'array_validation' => 'full' (100% exhaustive element scanning on every array and shape):
Mode (array_validation => 'full') | Duration | Overhead |
|---|---|---|
TypePHP Disabled (TYPEPHP_DISABLE=true) | 54.46s | Baseline |
| TypePHP Enabled | 55.12s | +0.66s (~1.2%) |
Even under exhaustive full mode, in typical web frameworks (Laravel, Symfony, Shopware) where database queries, container resolution, HTTP routing, and I/O dominate wall-clock time, TypePHP's runtime checking overhead sits around 1%. Practically indistinguishable from normal run-to-run variance. The kind of number that makes the "but runtime type checking is too slow" argument start to look a little silly.
Conclusion: Clean Outside, Fast Inside
Clean code principles are meant to serve maintainability. They are not supposed to become a tax you pay on every single iteration of an inner loop. I learned that the hard way, with 118 milion function calls staring me in the face.
Performance-critical and sensitive software like TypePHP simply cannot afford clean code on the hot paths at runtime. Every extra abstraction, every polite interface hop, every shared helper that looks nice in the IDE turns into real cost when it runs millions of times. On those paths you have to get mechanical and a little ugly.
That said, for typical PHP applications where most of the work is I/O (database queries, HTTP calls, file access, queue jobs), clean code is still a must. The overhead of nice abstractions is usually drowned out by waiting on the network or disk, so the maintainability win is worth it.
The balance I found in TypePHP is pretty straightforward: keep the cold paths clean, modular, and easy to reason about. Treat the hot paths with actual mechanical sympathy for the PHP runtime. When a pure userland PHP checker can enforce full generics, array shapes, and typestates at 3.5 milion operations per second, clear 6,928 generic collection tests in 8.6 seconds, and add only ~1% overhead on a real Laravel suite, the old trade-off starts to look outdated.
And for the record: PHP is not slow. It gets slow when you fight it with excessive abstraction, endless indirection, and polite OOP rituals on the hot path. When you actually sympatize with how the runtime works (inline the boring stuff, cache the expensive stuff, eliminate what you can at compile time), it can be surprisingly fast. TypePHP is living proof of that. The language was never the problem. The architecure often was.
Want to dig deeper into the engine internals or tune TypePHP for production? Read the Performance Considerations Guide or try it live in the Interactive WebAssembly Playground.