Skip to content

Performance: super-linear analysis on literal-union !== narrowing chains #15004

Closed
phpstan/phpstan-src
#5857

Description

@SanderMuller

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 (exact UnionType only, no class-string constant strings,
    no floats). Precedented, self-contained, low risk. Cheapens each remove call.
  • B, fix the flattening path. The plain-string version 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

  1. mergeable commented on Jul 27, 2026

    @mergeable

    This bug report is missing a link to reproduction at phpstan.org/try.

    It will most likely be closed after manual review.

  2. staabm commented on Jul 27, 2026

    @staabm
    Contributor

    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:

    Image

    and the following hot path starting from NodeScopeResolver->processStmtNode:
    (very deep resolveType, getType recursion)

    Image

    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

  3. staabm commented on Jul 27, 2026

    @staabm
    Contributor

    I can see we spend a lot of time in UnionType::isSubTypeOf... we could try to implement a IsSuperTypeOfResult::lazyExtremeIdentity variant, similar to TrinaryLogic::lazyExtremeIdentity.

    maybe its more efficient for this case

  4. staabm commented on Jul 27, 2026

    @staabm
    Contributor

    turning the reproducer into a int range like

    <?php
    /** @param int<1, 200> $x */
    function g(int $x): void {
     if ($x !== 1 && $x !== 2 && $x !== 3 && $x !== 4 && $x !== 5 && $x !== 6 && $x !== 7 && $x !== 8 && $x !== 9 && $x !== 10 && $x !== 11 && $x !== 12 && $x !== 13 && $x !== 14 && $x !== 15 && $x !== 16 && $x !== 17 && $x !== 18 && $x !== 19 && $x !== 20 && $x !== 21 && $x !== 22 && $x !== 23 && $x !== 24 && $x !== 25 && $x !== 26 && $x !== 27 && $x !== 28 && $x !== 29 && $x !== 30 && $x !== 31 && $x !== 32 && $x !== 33 && $x !== 34 && $x !== 35 && $x !== 36 && $x !== 37 && $x !== 38 && $x !== 39 && $x !== 40 && $x !== 41 && $x !== 42 && $x !== 43 && $x !== 44 && $x !== 45 && $x !== 46 && $x !== 47 && $x !== 48 && $x !== 49 && $x !== 50 && $x !== 51 && $x !== 52 && $x !== 53 && $x !== 54 && $x !== 55 && $x !== 56 && $x !== 57 && $x !== 58 && $x !== 59 && $x !== 60 && $x !== 61 && $x !== 62 && $x !== 63 && $x !== 64 && $x !== 65 && $x !== 66 && $x !== 67 && $x !== 68 && $x !== 69 && $x !== 70 && $x !== 71 && $x !== 72 && $x !== 73 && $x !== 74 && $x !== 75 && $x !== 76 && $x !== 77 && $x !== 78 && $x !== 79 && $x !== 80 && $x !== 81 && $x !== 82 && $x !== 83 && $x !== 84 && $x !== 85 && $x !== 86 && $x !== 87 && $x !== 88 && $x !== 89 && $x !== 90 && $x !== 91 && $x !== 92 && $x !== 93 && $x !== 94 && $x !== 95 && $x !== 96 && $x !== 97 && $x !== 98 && $x !== 99 && $x !== 100 && $x !== 101 && $x !== 102 && $x !== 103 && $x !== 104 && $x !== 105 && $x !== 106 && $x !== 107 && $x !== 108 && $x !== 109 && $x !== 110 && $x !== 111 && $x !== 112 && $x !== 113 && $x !== 114 && $x !== 115 && $x !== 116 && $x !== 117 && $x !== 118 && $x !== 119 && $x !== 120 && $x !== 121 && $x !== 122 && $x !== 123 && $x !== 124 && $x !== 125 && $x !== 126 && $x !== 127 && $x !== 128 && $x !== 129 && $x !== 130 && $x !== 131 && $x !== 132 && $x !== 133 && $x !== 134 && $x !== 135 && $x !== 136 && $x !== 137 && $x !== 138 && $x !== 139 && $x !== 140 && $x !== 141 && $x !== 142 && $x !== 143 && $x !== 144 && $x !== 145 && $x !== 146 && $x !== 147 && $x !== 148 && $x !== 149 && $x !== 150 && $x !== 151 && $x !== 152 && $x !== 153 && $x !== 154 && $x !== 155 && $x !== 156 && $x !== 157 && $x !== 158 && $x !== 159 && $x !== 160 && $x !== 161 && $x !== 162 && $x !== 163 && $x !== 164 && $x !== 165 && $x !== 166 && $x !== 167 && $x !== 168 && $x !== 169 && $x !== 170 && $x !== 171 && $x !== 172 && $x !== 173 && $x !== 174 && $x !== 175 && $x !== 176 && $x !== 177 && $x !== 178 && $x !== 179 && $x !== 180 && $x !== 181 && $x !== 182 && $x !== 183 && $x !== 184 && $x !== 185 && $x !== 186 && $x !== 187 && $x !== 188 && $x !== 189 && $x !== 190 && $x !== 191 && $x !== 192 && $x !== 193 && $x !== 194 && $x !== 195 && $x !== 196 && $x !== 197 && $x !== 198 && $x !== 199 && $x !== 200) { echo "none"; }
    }
    

    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

  5. staabm commented on Jul 27, 2026

    @staabm
    Contributor

    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

    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

  6. staabm commented on Aug 11, 2026

    @staabm
    Contributor

    after phpstan/phpstan-src#6116 was merged, the bottleneck now is in UnionType->getFiniteTypes(), see blackfire profile:

    Image

    I think it can be made faster utilizing FiniteTypeSet

  7. staabm commented on Aug 11, 2026

    @staabm
    Contributor

    @SanderMuller please re-evaluate the initital example. I think we are now good enough for the given reproducer

  8. SanderMuller commented on Aug 11, 2026

    @SanderMuller
    ContributorAuthor

    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:

    N 2.2.6 2.2.8 2.2.x-dev (be4165f)
    50 0.92s 0.89s 0.89s
    100 1.77s 1.46s 1.46s
    200 7.87s 5.18s 5.16s
    300 23.86s 14.55s 15.04s
    400 56.14s 32.14s 32.30s

    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:

    N 2.2.x-dev
    400 32.3s
    600 104.0s
    800 241.9s

    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::remove counterpart of the intersect blowup 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.

  9. staabm commented on Aug 11, 2026

    @staabm
    Contributor

    Feel free to propose a fix

  10. SanderMuller commented on Aug 12, 2026

    @SanderMuller
    ContributorAuthor

    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,295 remove calls 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 puts remove at 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: BooleanOrHandler flattens deep chains in both resolveType() and specifyTypes(); BooleanAndHandler flattened only specifyTypes(), 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 their BooleanOr counterparts.

    Suite green, self-analysis clean, and output byte-identical on a real 1144-file application (where CPU is also 3.2% lower).

  11. github-actions commented on Oct 4, 2026

    @github-actions

    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.

  12. locked as resolved and limited conversation to collaborators on Oct 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions