Skip to content

fix(js): String.length walks Char width instead of expanding the string - #1652

Open
adeerkhan wants to merge 1 commit into
bendlang:mainfrom
adeerkhan:fix/js-string-length
Open

adeerkhan wants to merge 1 commit into
bendlang:mainfrom
adeerkhan:fix/js-string-length

Conversation

@adeerkhan

Copy link
Copy Markdown

Resolves #1612.

The JS string_length intrinsic was [...str_out($0)].length, which builds a whole expanded copy of the string just to count its Chars — O(n) temporary storage, including a second representation of every supplementary character.

Replace it with a string_length(s) helper that walks the string with the existing Char-width decoder (char_len) and a counter: O(n) time, O(1) space. This reuses the same char_len the runtime already trusts (e.g. string_contains), so it counts a packed U32 Char (4 UTF-16 units) as one Char and an astral scalar (2 units) as one Char, exactly as before.

Verified equivalence against the previous [...str_out(s)].length for ASCII, astral, and packed-U32-Char strings.

The JS string_length intrinsic built [...str_out(s)], a whole expanded copy of
the string, just to count its Chars. Replace it with a string_length helper
that walks the string with the existing Char-width decoder (char_len) and a
counter, so counting is O(n) time and O(1) space. Resolves bendlang#1612.
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.

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

1 participant