Skip to content

perf: fix O(T²) list copies in CopyVisitor.addition#189

Merged
tbittar merged 1 commit intomainfrom
fix/addition-complexity
Mar 25, 2026
Merged

perf: fix O(T²) list copies in CopyVisitor.addition#189
tbittar merged 1 commit intomainfrom
fix/addition-complexity

Conversation

@tbittar
Copy link
Copy Markdown
Collaborator

@tbittar tbittar commented Mar 24, 2026

Summary

  • CopyVisitor inherited the default addition() from ExpressionVisitorOperations, which accumulated visited operands with res = res + o in a loop. The flattening __add__ on ExpressionNode copies the accumulated operand list at each step, giving O(T²) total list copies for a T-term AdditionNode.
  • Fix overrides addition() in CopyVisitor to build the AdditionNode directly from a list comprehension — O(T).
  • Adds a regression test asserting the time ratio between T=10,000 and T=1,000 stays below 20 (linear ≈ 10×, quadratic ≈ 100×).

This is Fix 2 from the superlinear complexity analysis (see issue #188).

Test plan

  • pytest tests/unittests/expressions/visitor/test_copy.py — both tests pass, including the new test_copy_large_addition_is_linear
  • Full suite: pytest tests/ passes

🤖 Generated with Claude Code

The default `addition` in ExpressionVisitorOperations accumulated results
with `res = res + o` in a loop. The flattening `__add__` on ExpressionNode
copies the accumulated operand list at each step, giving O(T²) total copy
work for a T-term AdditionNode.

Override `addition` in CopyVisitor to build the AdditionNode directly from
a list comprehension, reducing the cost to O(T).

Add a regression test that asserts the time ratio between T=10_000 and
T=1_000 stays below 20 (linear ≈ 10, quadratic ≈ 100).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@tbittar tbittar requested a review from aoustry March 24, 2026 21:44
@tbittar tbittar merged commit 20021bf into main Mar 25, 2026
2 checks passed
@tbittar tbittar deleted the fix/addition-complexity branch March 25, 2026 09:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants