perf(uuid): make uuidToBytes() up to 2.5x faster (#5670)

perf(uuid): make `uuidToBytes` up to 2.5x faster
This commit is contained in:
David Luis 2024-08-10 13:48:05 +07:00 committed by GitHub
parent d5e31807c5
commit 1428c9c94c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -45,9 +45,35 @@ export function bytesToUuid(bytes: number[] | Uint8Array): string {
* @param uuid Value that gets converted. * @param uuid Value that gets converted.
*/ */
export function uuidToBytes(uuid: string): Uint8Array { export function uuidToBytes(uuid: string): Uint8Array {
const bytes = uuid const bytes = new Uint8Array(16);
.replaceAll("-", "") let i = 0;
.match(/.{1,2}/g)!
.map((byte) => parseInt(byte, 16)); for (const str of uuid.split("-")) {
return new Uint8Array(bytes); 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;
} }