From f5100d32252083ebb14092633381397361f9b960 Mon Sep 17 00:00:00 2001 From: Spotandjake <40705786+spotandjake@users.noreply.github.com> Date: Wed, 24 Jan 2024 23:04:54 -0500 Subject: [PATCH] chore(stdlib): Optimize `Array.join` (#1948) --- stdlib/array.gr | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/stdlib/array.gr b/stdlib/array.gr index 09192ec713..6e3172a615 100644 --- a/stdlib/array.gr +++ b/stdlib/array.gr @@ -884,17 +884,30 @@ provide let unzip = array => { * * @since v0.4.0 */ +@unsafe provide let join = (separator: String, items: Array) => { - let iter = (acc, str) => { - match (acc) { - None => Some(str), - Some(prev) => Some(prev ++ separator ++ str), - } - } - match (reduce(iter, None, items)) { - None => "", - Some(s) => s, - } + from WasmI32 use { (+), (==) } + from DataStructures use { allocateString, stringSize } + let arrLen = length(items) + let sepPtr = WasmI32.fromGrain(separator) + let sepSize = stringSize(sepPtr) + let sepPtr = sepPtr + 8n + let mut strSize = 0n + for (let mut i = 0; i < arrLen; i = incr(i)) { + strSize += stringSize(WasmI32.fromGrain(items[i])) + if (i != 0) strSize += sepSize + } + let newString = allocateString(strSize) + let mut offset = newString + 8n + for (let mut i = 0; i < arrLen; i = incr(i)) { + let ptr = WasmI32.fromGrain(items[i]) + let size = stringSize(ptr) + Memory.copy(offset, ptr + 8n, size) + offset += size + if (i != arrLen) Memory.copy(offset, sepPtr, sepSize) + offset += sepSize + } + WasmI32.toGrain(newString): String } /**