Skip to content

MIR: a string self-append after an if statement copies the whole string (lower_if forgets string flow facts): s = s ++ f() in a loop is quadratic #1491

Closed

Description

@ehartford

Found while fixing #1358 (with ast quadratic). The renderer's list loops are the common shape

var out = "["
for i in 0..count:
    if i > 0:
        out = out ++ ", "
    out = out ++ elem(i)

try_lower_string_self_concat_assign (src/MirLower.w) lowers out = out ++ x to the in-place, geometrically growing with_str_concat_n_move_first only while string_place_may_alias(out) is 0. lower_if ends with self.forget_string_flow_facts() at its join block, which marks every str place may-alias, so the append after any if statement is lowered to the copying with_str_concat_n (a fresh exact-size buffer and a copy of all of out) — for the rest of the loop body, forever. The same happens after if_let, while, loop, for exits and the other forget sites.

IR of three variants (installed v0.15.2.1, with ir -O1):

body of the for appends lowered to
out = out ++ elem(i) with_str_concat_n_move_first
if i > 0: out = out ++ ", " then out = out ++ elem(i) move_first, then with_str_concat_n
same, with a statement after the if body's append move_first, then with_str_concat_n

Timing of the second shape as a standalone program (lit(n) returning the joined string): n=64000 9.47 s, n=256000 117.6 s; sample: 1468 of 1715 samples in str_concat_n_copy, 204 in with_str_concat_n_move_first.

Nothing in the if arms aliased out; the join should merge the arms' facts (may-alias if any arm aliased, owned if every arm left it owned) instead of forgetting them. This is aliasing-safety code (move_first frees the old buffer when it grows), so it wants its own batch with :drop-audit.

#1358's renderer no longer depends on this (it builds its lists in StringBuilders), but every user program that builds a string with a separator does.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions