Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 1 commit into from
Aug 8, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 32 additions & 15 deletions uuid/_common.ts
Original file line number Diff line number Diff line change
@@ -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();
}

/**
Expand Down