Skip to content

Commit

Permalink
stdlib: improve perf of uuid
Browse files Browse the repository at this point in the history
Utilize a pool for rng. Improves throughput approx 6 times.
This fix is brought by upstream uuidjs/uuid#513
  • Loading branch information
dirkdev98 committed Sep 5, 2020
1 parent 07ec7f6 commit f219767
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
2 changes: 0 additions & 2 deletions packages/cli/src/benchmarking/printer.js
Expand Up @@ -11,8 +11,6 @@ export function printBenchResults() {
}
}

benchLogger.info(state);

const result = [];

result.push("");
Expand Down
15 changes: 10 additions & 5 deletions packages/stdlib/src/vendor/uuid.js
Expand Up @@ -26,7 +26,8 @@

import { randomFillSync } from "crypto";

const rnds8 = new Uint8Array(16);
const randomPool = new Uint8Array(256); // # of random values to pre-allocate
let poolPtr = randomPool.length;
const byteToHex = [];

for (let i = 0; i < 256; ++i) {
Expand Down Expand Up @@ -60,11 +61,15 @@ function bytesToUuid(buf, offset) {
*
*/
export function v4() {
const rnds = randomFillSync(rnds8);
if (poolPtr > randomPool.length - 16) {
randomFillSync(randomPool);
poolPtr = 0;
}
const buffer = randomPool.slice(poolPtr, (poolPtr += 16));

// Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
rnds[6] = (rnds[6] & 0x0f) | 0x40;
rnds[8] = (rnds[8] & 0x3f) | 0x80;
buffer[6] = (buffer[6] & 0x0f) | 0x40;
buffer[8] = (buffer[8] & 0x3f) | 0x80;

return bytesToUuid(rnds);
return bytesToUuid(buffer);
}

0 comments on commit f219767

Please sign in to comment.