bits = crypto.getRandomValues(new Uint8Array(20))
bits[5] = (bits[5] & 0x4F) | 0x40;
bits[8] = (bits[8] & 0xBF) | 0x80;
bits = [bits].map(e => e.toString(16).padStart(2,'0') ).reduce((a,c,i)=>a+([4,7,10,13].includes(i)?'-':c));
Array(20).fill(0).map(()=>crypto.getRandomValues(new Uint8Array(1))[0].toString(16).padStart(2,'0')).reduce((a,c,i)=>a+([4,7,10,13].includes(i)?'-':c))
([1e3]+-10+-10+-1e5).replace(/\d/g, () => crypto.getRandomValues(new Uint8Array(1))[0].toString(16).padStart(2,'0'))
let s=[]; crypto.getRandomValues(new Uint8Array(20)).map( e => s.push(e.toString(16).padStart(2,'0')) ); [4,7,10,13].map( idx => s[idx]='-' ); s.join('');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
uuidv4 | |
random 1 | |
random 2 | |
random 3 |
Test name | Executions per second |
---|---|
uuidv4 | 207746.5 Ops/sec |
random 1 | 24495.9 Ops/sec |
random 2 | 33988.7 Ops/sec |
random 3 | 240736.8 Ops/sec |
Let's break down the provided benchmarking JSON and explain what's being tested.
Benchmark Overview
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks. The goal of this benchmark is to measure the performance of different approaches for generating UUIDs (Universally Unique Identifiers) using the crypto
module in JavaScript.
UUID Generation Methods
The benchmark tests four different methods for generating UUIDs:
crypto.getRandomValues
function to generate 20 random bytes, then modifies them according to a specific pattern. The resulting UUID is generated by reducing the modified bytes into a string.crypto.getRandomValues
, converts each value to a hexadecimal string, and then reduces these strings together with some modifications.random 1
, but uses a different pattern for modifying the generated values.s
and pushes the generated random bytes into it as hexadecimal strings, followed by replacing specific indices with hyphens.Library and Syntax
In this benchmark, the crypto
module is used extensively. The getRandomValues
function is a part of this module, which returns an array of random numbers.
There are no special JavaScript features or syntaxes being tested in this benchmark.
Comparison of Approaches
The pros and cons of each approach are:
uuidv4
, but they also provide more opportunities for optimization (e.g., caching or memoization). However, their increased complexity may lead to slower execution times.Other Alternatives
If you're looking for alternative methods to generate UUIDs in JavaScript, consider using a dedicated library like uuid
or nanoid
. These libraries provide a simple and efficient way to generate UUIDs without relying on the crypto
module.
In conclusion, this benchmark tests four different approaches for generating UUIDs using the crypto
module. The choice of approach depends on trade-offs between performance, readability, and complexity.