From 2f28b8b80e3f5daaaf9d11df661607541293c6c6 Mon Sep 17 00:00:00 2001 From: Ingvar Stepanyan Date: Mon, 1 Apr 2019 13:08:08 +0100 Subject: [PATCH] Optimise encodeInto reallocations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- crates/cli-support/src/js/mod.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/crates/cli-support/src/js/mod.rs b/crates/cli-support/src/js/mod.rs index 4a9fabcd..fdbb2199 100644 --- a/crates/cli-support/src/js/mod.rs +++ b/crates/cli-support/src/js/mod.rs @@ -1306,13 +1306,12 @@ impl<'a> Context<'a> { while (true) {{ const view = getUint8Memory().subarray(ptr + writeOffset, ptr + size); const {{ read, written }} = cachedTextEncoder.encodeInto(arg, view); - arg = arg.substring(read); - writeOffset += written; - if (arg.length === 0) {{ + if (read === arg.length) {{ break; }} - ptr = wasm.__wbindgen_realloc(ptr, size, size * 2); - size *= 2; + arg = arg.substring(read); + writeOffset += written; + ptr = wasm.__wbindgen_realloc(ptr, size, size += arg.length * 3); }} WASM_VECTOR_LEN = writeOffset; return ptr;