Skip to content

Commit 2f28b8b

Browse files
committed
Optimise encodeInto reallocations
Instead of doubling the size on each iteration, use precise upper limit (3 * JS length) if the string turned out not to be ASCII-only. This results in maximum of 1 reallocation instead of O(log N). Some dummy examples of what this would change: - 1000 of ASCII chars: no change, allocates 1000 bytes and bails out. - 1000 ASCII chars + 1 '😃': before allocated 1000 bytes and reallocated to 2000; now allocates 1000 bytes and reallocates to 1006. - 1000 of '😃' chars: before allocated 1000 bytes, reallocated to 2000, finally reallocated again to 4000; now allocates 1000 bytes and reallocates to 4000 right away. Related issue: #1313
1 parent 1121393 commit 2f28b8b

File tree

1 file changed

+4
-5
lines changed
  • crates/cli-support/src/js

1 file changed

+4
-5
lines changed

crates/cli-support/src/js/mod.rs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1306,13 +1306,12 @@ impl<'a> Context<'a> {
13061306
while (true) {{
13071307
const view = getUint8Memory().subarray(ptr + writeOffset, ptr + size);
13081308
const {{ read, written }} = cachedTextEncoder.encodeInto(arg, view);
1309-
arg = arg.substring(read);
1310-
writeOffset += written;
1311-
if (arg.length === 0) {{
1309+
if (read === arg.length) {{
13121310
break;
13131311
}}
1314-
ptr = wasm.__wbindgen_realloc(ptr, size, size * 2);
1315-
size *= 2;
1312+
arg = arg.substring(read);
1313+
writeOffset += written;
1314+
ptr = wasm.__wbindgen_realloc(ptr, size, size += arg.length * 3);
13161315
}}
13171316
WASM_VECTOR_LEN = writeOffset;
13181317
return ptr;

0 commit comments

Comments
 (0)