Skip to content

Commit 2e898a4

Browse files
committed
fix(core): Improve uuid performance
1 parent c68674a commit 2e898a4

File tree

1 file changed

+11
-17
lines changed

1 file changed

+11
-17
lines changed

packages/core/src/utils/misc.ts

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import { snipLine } from './string';
77
import { GLOBAL_OBJ } from './worldwide';
88

99
interface CryptoInternal {
10-
getRandomValues(array: Uint8Array): Uint8Array;
1110
randomUUID?(): string;
1211
}
1312

@@ -22,37 +21,32 @@ function getCrypto(): CryptoInternal | undefined {
2221
return gbl.crypto || gbl.msCrypto;
2322
}
2423

24+
let emptyUuid: string | undefined;
25+
2526
/**
2627
* UUID4 generator
2728
* @param crypto Object that provides the crypto API.
2829
* @returns string Generated UUID4.
2930
*/
3031
export function uuid4(crypto = getCrypto()): string {
31-
let getRandomByte = (): number => Math.random() * 16;
3232
try {
3333
if (crypto?.randomUUID) {
3434
return crypto.randomUUID().replace(/-/g, '');
3535
}
36-
if (crypto?.getRandomValues) {
37-
getRandomByte = () => {
38-
// crypto.getRandomValues might return undefined instead of the typed array
39-
// in old Chromium versions (e.g. 23.0.1235.0 (151422))
40-
// However, `typedArray` is still filled in-place.
41-
// @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#typedarray
42-
const typedArray = new Uint8Array(1);
43-
crypto.getRandomValues(typedArray);
44-
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
45-
return typedArray[0]!;
46-
};
47-
}
4836
} catch {
4937
// some runtimes can crash invoking crypto
5038
// https://github.com/getsentry/sentry-javascript/issues/8935
5139
}
5240

53-
// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523
54-
// Concatenating the following numbers as strings results in '10000000100040008000100000000000'
55-
return (([1e7] as unknown as string) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c =>
41+
const getRandomByte = (): number => Math.random() * 16;
42+
43+
if (!emptyUuid) {
44+
// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523
45+
// Concatenating the following numbers as strings results in '10000000100040008000100000000000'
46+
emptyUuid = (([1e7] as unknown as string) + 1e3 + 4e3 + 8e3 + 1e11);
47+
}
48+
49+
return emptyUuid.replace(/[018]/g, c =>
5650
// eslint-disable-next-line no-bitwise
5751
((c as unknown as number) ^ ((getRandomByte() & 15) >> ((c as unknown as number) / 4))).toString(16),
5852
);

0 commit comments

Comments
 (0)