Skip to content

JS String.length allocates an array proportional to the whole string #1612

Closed as not planned

Description

@oxura

The JS String.length intrinsic expands the whole string with [...str_out(s)] just to count its characters. That adds O(n) temporary storage, including a second representation of every supplementary Unicode character.

I compiled this real Bend consumer on 7e120d5:

import Base

def payload() -> IO(String):
  import "./payload.js"

def main() -> IO(Unit):
  do IO<Unit>:
    s : String <- payload()
    IO.print(Nat.show(String.length(s)))
function payload() { return "😀".repeat(2000000); }
io_eff(CID(payload), payload);

It correctly prints 2000000, but three fresh Bun processes peak at 170988, 171744 and 170592 KiB RSS (/usr/bin/time -f %M bun program.js). The payload itself is four million UTF-16 code units; counting it should not require a two-million-element array. Current main keeps the same intrinsic.

The existing internal Char-width decoder can walk the string with an offset and a counter, preserving arbitrary U32 Chars as well as Unicode scalars without text-edge conversion. I am checking that change against the existing Char/string regressions and the same payload. AI-assisted investigation.

Activity

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