From 1e2cee7060dcca6a72335490233bc17185304f63 Mon Sep 17 00:00:00 2001 From: Siyuan Miao Date: Thu, 11 Sep 2025 02:56:47 +0200 Subject: [PATCH] fix: performance issue of Uint8Array concat --- ui/src/hooks/hidRpc.ts | 22 +++++++++++++++------- ui/src/hooks/useHidRpc.ts | 1 - 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/ui/src/hooks/hidRpc.ts b/ui/src/hooks/hidRpc.ts index edf75e75..cf2ef9cc 100644 --- a/ui/src/hooks/hidRpc.ts +++ b/ui/src/hooks/hidRpc.ts @@ -232,15 +232,20 @@ export class KeyboardMacroReportMessage extends RpcMessage { } marshal(): Uint8Array { - const dataHeader = new Uint8Array([ + // validate if length is correct + if (this.length !== this.steps.length) { + throw new Error(`Length ${this.length} is not equal to the number of steps ${this.steps.length}`); + } + + const data = new Uint8Array(this.length * 9 + 6); + data.set(new Uint8Array([ this.messageType, this.isPaste ? 1 : 0, ...fromUint32toUint8(this.length), - ]); + ]), 0); - let dataBody = new Uint8Array(); - - for (const step of this.steps) { + for (let i = 0; i < this.length; i++) { + const step = this.steps[i]; if (!withinUint8Range(step.modifier)) { throw new Error(`Modifier ${step.modifier} is not within the uint8 range`); } @@ -264,10 +269,13 @@ export class KeyboardMacroReportMessage extends RpcMessage { ...keys, ...fromUint16toUint8(step.delay), ]); + const offset = 6 + i * 9; - dataBody = new Uint8Array([...dataBody, ...macroBinary]); + + data.set(macroBinary, offset); } - return new Uint8Array([...dataHeader, ...dataBody]); + + return data; } } diff --git a/ui/src/hooks/useHidRpc.ts b/ui/src/hooks/useHidRpc.ts index fecb1661..ddfea95b 100644 --- a/ui/src/hooks/useHidRpc.ts +++ b/ui/src/hooks/useHidRpc.ts @@ -75,7 +75,6 @@ export function useHidRpc(onHidRpcMessage?: (payload: RpcMessage) => void) { (macro: KeyboardMacroStep[]) => { const d = new KeyboardMacroReportMessage(false, macro.length, macro); sendMessage(d); - console.log("Sent keyboard macro report", d, d.marshal()); }, [sendMessage], );