Repository navigation
Description
Bug report
This is a performance report, not a wrong-output one. The reported errors are
correct; analysis is just slow. Time grows super-linearly when a variable typed
as a literal union (1|2|...|N) is narrowed by a long && chain of !==
comparisons: about 54s for a single 400-clause function on 2.2.6, roughly
O(N^2.7).
It is the last open shape from #14868. Two of the three shapes catalogued there
are fixed (the === assignment blowup in 2.2.3 via #5935, and match (true) in
2.2.5); this !== chain is not. It is the TypeCombinator::remove counterpart
of the intersect blowup that #5935 fixed.
Reproducer, synthetic, no dependencies:
php -r '$n=400;$doc="1";for($i=2;$i<=$n;$i++)$doc.="|$i";$cond="\$x !== 1";for($i=2;$i<=$n;$i++)$cond.=" && \$x !== $i";file_put_contents("repro.php","<?php\n/** @param $doc \$x */\nfunction g(int \$x): void {\n if ($cond) { echo \"none\"; }\n}\n");'
produces:
<?php
/** @param 1|2|3|...|400 $x */
function g(int $x): void {
if ($x !== 1 && $x !== 2 && /* ... */ && $x !== 400) {
echo "none";
}
}Measurements on released phars, level 8, single file, result cache cold, CPU as
user+sys, PHP 8.5.8. Scaling on 2.2.6:
| N | 50 | 100 | 200 | 300 | 400 |
|---|---|---|---|---|---|
| CPU | 0.38s | 1.29s | 7.72s | 23.75s | 54.3s |
Each doubling of N costs about 6 to 7 times as much, so roughly O(N^2.7). Flat
across 2.2.2 through 2.2.6, so it is neither a recent regression nor something
the intersect and match (true) fixes touched.
Root cause: each $x !== k clause narrows the subject in the truthy branch by
removing one constant from its union, so TypeCombinator::remove runs O(N) times
over an O(N)-wide union and rebuilds on each call. #14868 measured this as about
11M remove calls at N=200 on two-member unions. The timing and scaling above
are confirmed here; the call count is cited from #14868 and would be re-confirmed
with an instrumented counter while fixing, the way #5935 confirmed the intersect
count dropping from about 21M to linear.
The part worth settling before any code exists is which of two directions to take:
- A, mirror Reference class properties never read #5935 into
remove. A fast path for "constant-scalar union minus
constant-scalar union", a value-keyed set difference in O(N), with the same
exclusions Reference class properties never read #5935 used (exactUnionTypeonly, no class-string constant strings,
no floats). Precedented, self-contained, low risk. Cheapens eachremovecall. - B, fix the flattening path. The plain-
stringversion of this&&/||
shape is already handled by the boolean-chain flattening (guarded by
and-chain-truthy-blowup.php/or-chain-falsey-blowup.php), but a
literal-union subject appears to defeat it. Making the flattening fire here
would remove the calls rather than cheapen them. Deeper and riskier, closer to
fixing the algorithm than the symptom.
They are not exclusive. Two questions for you: is the boolean flattening
deliberately scoped to plain strings, or was the literal-union case just never
extended? And if both are viable, is a remove fast path worth landing on its
own even if the flattening is later fixed?
Ruled out: not the intersect blowup (fixed 2.2.3, #5935), not match (true)
(fixed 2.2.5), not configuration (bare -l 8 reproduces it and bleeding edge
makes no difference), not a phar-versus-source artifact (the 2.2.2 phar
reproduces it too), not a recent regression (flat across 2.2.2 through 2.2.6).
Code snippet that reproduces the problem
No phpstan.org/r link: this is a performance report, so the playground has
nothing to show (the output is correct, it is only slow, and the playground does
not surface timing). The full reproducer and generator are in the body above.
Expected output
The reported errors are already correct, so there is nothing to change in the
output. The problem is only speed. Analysis of this shape should be roughly
linear in the number of comparisons, the way the sibling === assignment and
match (true) shapes are now after #5935 and the 2.2.5 fix. Concretely, the
400-clause case should drop from about 54s to single-digit seconds.
Activity
mergeable commentedon Jul 27, 2026
This bug report is missing a link to reproduction at phpstan.org/try.
It will most likely be closed after manual review.
staabm commentedon Jul 27, 2026
running the reproducer on phpstan-src commit e6d7b5be5793343d950b01c720e55ef2c0d9446f takes arround 58 seconds on my macbook m4 pro with
PHP 8.3.32 (cli) (built: Jul 1 2026 08:57:05) (NTS).running the repro with n=200 thru the blackfire profiler leads to the following table with most time consuming methods/functions:
and the following hot path starting from
NodeScopeResolver->processStmtNode:(very deep
resolveType,getTyperecursion)a optimal solution would not need generalization so we don't loose analysis precision - not sure its doable though.
there might be some integer-only shortcuts via IntegerRangeType. not sure that would be useful, because we likely have the same problem for large constant string unions
staabm commentedon Jul 27, 2026
I can see we spend a lot of time in
UnionType::isSubTypeOf... we could try to implement aIsSuperTypeOfResult::lazyExtremeIdentityvariant, similar toTrinaryLogic::lazyExtremeIdentity.maybe its more efficient for this case
staabm commentedon Jul 27, 2026
turning the reproducer into a int range like
makes it 4-5x faster.. maybe we can make use of that knowledge and e.g. internally represent a UnionType more efficient as a union of int ranges instead of a union of const integers
staabm commentedon Jul 27, 2026
thinking more about the constant strings case.. I think the problem we solve here (checking whether a single string is contained in a array of strings) is similar to what routing classes do in MVC frameworks, when matching the current request-uri. maybe we can optimize the strings vs. union of strings superTypeOf/subTypeOf variant with a trie based Type.
edit: I will try this idea in a separate issue
Answer `isSubTypeOf()` against a single value from the `FiniteTypeSet…
Answer `isSubTypeOf()` against a single value from the `FiniteTypeSet…
Answer `isSubTypeOf()` against a single value from the `FiniteTypeSet…
Answer `isSubTypeOf()` against a single value from the `FiniteTypeSet…
staabm commentedon Aug 11, 2026
after phpstan/phpstan-src#6116 was merged, the bottleneck now is in
UnionType->getFiniteTypes(), see blackfire profile:I think it can be made faster utilizing
FiniteTypeSetstaabm commentedon Aug 11, 2026
@SanderMuller please re-evaluate the initital example. I think we are now good enough for the given reproducer
SanderMuller commentedon Aug 11, 2026
Re-evaluated. It did get meaningfully faster — about 1.75× — but I do not think the reproducer is good yet: the growth law is essentially unchanged, so the improvement is a constant factor on top of the same curve.
Same machine, same method as the original table (release phars, level 8, single file, cold result cache, CPU as user+sys, PHP 8.5.8), all three versions interleaved per N:
be4165f)My 2.2.6 column reproduces the issue's original table at the large end (7.72 / 23.75 / 54.3s there vs 7.87 / 23.86 / 56.14s now), so the harness is measuring the same thing. Current dev matches 2.2.8 to within noise, so nothing further has landed since the release. All three report the same 3 errors, so nothing changed behaviourally.
Fitting N=100→400: O(N^2.49) on 2.2.6, O(N^2.23) on 2.2.8. And extending the curve on dev rather than extrapolating it:
400→800 is ×7.5 for a doubling, i.e. ~O(N^2.9) at the top end — the curve steepens rather than flattening. A single 800-clause function costs four minutes of CPU.
So from my side the two things that would close it are unchanged: growth that is at least close to linear, or failing that, the 400-clause case landing in the low seconds instead of half a minute. Right now 32s for one function is still the kind of thing that shows up as a mysterious CI timeout.
If it helps, the direction in the report is still untouched as far as these numbers show — this is the
TypeCombinator::removecounterpart of theintersectblowup that phpstan/phpstan-src#5935 fixed, and a value-keyed set difference for "constant-scalar union minus constant-scalar union" would be the same shape of fix. Happy to measure any patch against the table above.staabm commentedon Aug 11, 2026
Feel free to propose a fix
SanderMuller commentedon Aug 12, 2026
Proposed: phpstan/phpstan-src#6214. 18.4s → 1.0s of CPU on the 400-clause reproducer, and the curve goes linear (per doubling of N: x3.41/x5.80 before, x1.21/x1.65 after).
Two things in my report above are wrong, and the PR corrects both:
The root cause is not
TypeCombinator::remove, and option A does not work. I built it first — a value-keyed set-difference fast path mirroring phpstan/phpstan-src#5935 — and it came out slightly slower (0.90x at N=400). The counters explain it: of 279,295removecalls at N=200 the fast path could serve 40,381, and every single one still had to rebuild the union. There is no cheap "value is not a member" case here to win, so it only adds a keying attempt in front of the same work. A subtractive probe putsremoveat 63% of the runtime, but with it stubbed out entirely the remainder is still quadratic — so the number of narrowing operations is the problem, not their unit cost.The plain-string version is not already handled by the flattening. I claimed that as the premise for option B. It is equally quadratic: 17.30s at N=400 versus 17.96s for the int version.
What it actually is:
BooleanOrHandlerflattens deep chains in bothresolveType()andspecifyTypes();BooleanAndHandlerflattened onlyspecifyTypes(), and only in a truthy context. Hence the operator asymmetry — same reproducer, same method,&&18.38s vs||0.98s at N=400. The PR adds the two missing halves as mirrors of theirBooleanOrcounterparts.Suite green, self-analysis clean, and output byte-identical on a real 1144-file application (where CPU is also 3.2% lower).
github-actions commentedon Oct 4, 2026
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.