Skip to content

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

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

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

Conversation

@adeerkhan

Copy link
Copy Markdown
Contributor

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.
@Lorenzobattistela

Copy link
Copy Markdown
Collaborator

Thanks for the clean patch. We're closing this one: the JS backend is Bend's reference runtime, and we don't want JS-only performance changes there (see #1644). The current [...str_out(s)].length already returns the right count; the cost is only temporary memory, and performance work belongs on the C side for now. #1612 and #1614 were closed for the same reason.

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

2 participants