From 1428c9c94c22a33e9cba4b11a70738f7af3a0274 Mon Sep 17 00:00:00 2001 From: David Luis <95457148+babiabeo@users.noreply.github.com> Date: Sat, 10 Aug 2024 13:48:05 +0700 Subject: [PATCH] perf(uuid): make `uuidToBytes()` up to 2.5x faster (#5670) perf(uuid): make `uuidToBytes` up to 2.5x faster --- uuid/_common.ts | 36 +++++++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/uuid/_common.ts b/uuid/_common.ts index 820375663..83a9d058e 100644 --- a/uuid/_common.ts +++ b/uuid/_common.ts @@ -45,9 +45,35 @@ export function bytesToUuid(bytes: number[] | Uint8Array): string { * @param uuid Value that gets converted. */ export function uuidToBytes(uuid: string): Uint8Array { - const bytes = uuid - .replaceAll("-", "") - .match(/.{1,2}/g)! - .map((byte) => parseInt(byte, 16)); - return new Uint8Array(bytes); + const bytes = new Uint8Array(16); + let i = 0; + + for (const str of uuid.split("-")) { + const hex = parseInt(str, 16); + switch (str.length) { + case 4: { + bytes[i++] = (hex >>> 8) & 0xff; + bytes[i++] = hex & 0xff; + break; + } + case 8: { + bytes[i++] = (hex >>> 24) & 0xff; + bytes[i++] = (hex >>> 16) & 0xff; + bytes[i++] = (hex >>> 8) & 0xff; + bytes[i++] = hex & 0xff; + break; + } + case 12: { + bytes[i++] = (hex / 0x10000000000) & 0xff; + bytes[i++] = (hex / 0x100000000) & 0xff; + bytes[i++] = (hex >>> 24) & 0xff; + bytes[i++] = (hex >>> 16) & 0xff; + bytes[i++] = (hex >>> 8) & 0xff; + bytes[i++] = hex & 0xff; + break; + } + } + } + + return bytes; }