Skip to content

perf: toStringAs appends digits and reverses once - #7

Merged
Unisay merged 1 commit into
masterfrom
issue-186/tostringas-append
Jul 13, 2026
Merged

perf: toStringAs appends digits and reverses once#7
Unisay merged 1 commit into
masterfrom
issue-186/tostringas-append

Conversation

@Unisay

Copy link
Copy Markdown
Collaborator

Problem

toStringAs built its digit sequence with table.insert(t, 1, digit), shifting the whole accumulated table on every loop iteration, quadratic in the digit count. For Int the digit count is bounded (at most 32 in radix 2), so in practice this is a constant-factor cost on a hot formatting path rather than an asymptotic blowup. Flagged by the fork-FFI performance audit, purescript-lua/purescript-lua#186.

Change

Digits come out of the division loop least-significant first; append them and reverse the joined string once. Each digit is a single ASCII byte for every radix up to 36, so string.reverse cannot split a character. Output is unchanged.

Verification

scripts/test is green: all 71 regression checks, including the multi-digit, negative and max-Int toStringAs cases that pin digit order (a reversal mistake flips 100 into 001). Measured on 31-digit binary rendering (toStringAs 2 2147483647, 2·10⁵ reps): 1.5× faster under LuaJIT (0.355 s → 0.240 s), 1.6× under PUC Lua 5.1 (1.634 s → 0.992 s).

Suggested release: patch (v6.1.3) plus a package-set bump.

Refs purescript-lua/purescript-lua#186.

table.insert(t, 1, digit) shifts the whole accumulated table on every
loop iteration — quadratic in the digit count (bounded at 32 for Int,
so a constant-factor cost in practice). Append least-significant-first
and reverse the joined string instead; each digit is a single ASCII
byte, so string reverse is safe for every radix up to 36. Measured
1.5-1.6x on 31-digit binary rendering (LuaJIT and PUC 5.1).
Refs purescript-lua/purescript-lua#186.
@Unisay
Unisay merged commit f0831bc into masterJul 13, 2026
1 check passed
@Unisay
Unisay deleted the issue-186/tostringas-append branch July 13, 2026 13:59
Sign up for freeto 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.

1 participant

@Unisay