Skip to content

[complexity, flattening, checker] O(n^2) — Checking a call copies its growing argument list each time #1956

Closed

Description

@pjcavalcanti

Consider these programs:

type Unit is Data:
  U{}

def discard(x1: Unit, x2: Unit) -> Unit:
  U{}
def example() -> Unit:
  discard(U{}, U{})
type Unit is Data:
  U{}

def discard(x1: Unit, x2: Unit, x3: Unit) -> Unit:
  U{}
def example() -> Unit:
  discard(U{}, U{}, U{})

discard ignores its arguments and returns U{}. Let n be the number of arguments
passed to discard: 2 and 3 above. Checking example copies
0 + 1 + ... + (n-1) = n(n-1)/2 existing argument-list entries:
1 and 3, respectively. Checking discard is separate.

Cause. Bend represents a call as nested applications. On each step towards the
called function, term_infer builds [tm.x, ...sp], where sp holds pending
arguments. Adding one argument copies every argument already collected.

This quadratic list work may not be necessary. A linked list could add each
argument with one node pointing to the existing list. Building it and converting
it to an array once would take O(n) work.

The same copying occurs when body_flatten loads ordinary parameters with repeated
vars.slice(1) calls: n parameters copy n(n-1)/2 entries to emit n lambdas.
Keeping the original array and advancing an index could make this list work O(n).

Constructor matching also copies growing field arrays for the recursion check and
the branch's type. With n fields, each loop copies n(n-1)/2 entries. Each generated
function could keep a linked prefix and build the ordered array once all fields
are present, giving O(n) list work including conversion.

To reproduce on main 7a7e6505a, save either program as example.bend;
run bun bend2/main.ts example.bend --check-only.

Source: pending arguments, argument consumers,
binder-tail copies, recursion fields, branch-type fields.

Activity

  1. pjcavalcanti commented on Nov 2, 2026

    @pjcavalcanti
    CollaboratorAuthor

    Addendum — 2 November 2026

    Adding one pending argument need not copy the arguments already collected, regardless of what the called function does. The saving therefore does not depend on discard ignoring its arguments.

    Constructor-field functions can be opened more than once. Their previously collected fields must remain unchanged: one mutable array shared between openings would violate that. A linked prefix could preserve those earlier values and produce an ordered array when complete. Building that final array must be included in the O(n) list work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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