perf(uuid): make bytesToUuid() up to 100x faster (#5655)

perf(uuid): make `bytesToUuid()` 100x faster
This commit is contained in:
David Luis 2024-08-08 16:45:56 +07:00 committed by GitHub
parent 96d70203cd
commit 0333255ead
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,26 +1,43 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
const hexTable: string[] = [];
for (let i = 0; i < 256; ++i) {
hexTable.push(i < 0x10 ? "0" + i.toString(16) : i.toString(16));
}
/**
* Converts the byte array to a UUID string
* @param bytes Used to convert Byte to Hex
*/
export function bytesToUuid(bytes: number[] | Uint8Array): string {
const bits = [...bytes].map((bit) => {
const s = bit.toString(16);
return bit < 0x10 ? "0" + s : s;
});
return [
...bits.slice(0, 4),
"-",
...bits.slice(4, 6),
"-",
...bits.slice(6, 8),
"-",
...bits.slice(8, 10),
"-",
...bits.slice(10, 16),
].join("");
return (
hexTable[bytes[0]!]! +
hexTable[bytes[1]!]! +
hexTable[bytes[2]!]! +
hexTable[bytes[3]!]! +
"-" +
hexTable[bytes[4]!]! +
hexTable[bytes[5]!]! +
"-" +
hexTable[bytes[6]!]! +
hexTable[bytes[7]!]! +
"-" +
hexTable[bytes[8]!]! +
hexTable[bytes[9]!]! +
"-" +
hexTable[bytes[10]!]! +
hexTable[bytes[11]!]! +
hexTable[bytes[12]!]! +
hexTable[bytes[13]!]! +
hexTable[bytes[14]!]! +
hexTable[bytes[15]!]!
// Use .toLowerCase() to avoid the v8 engine memory issue
// when concatenating strings with "+" operator. See:
// - https://issues.chromium.org/issues/42206473
// - https://github.com/uuidjs/uuid/pull/434
).toLowerCase();
}
/**