<!--your preparation HTML code goes here-->
var registeredIds = new Set();
function generate() {
let id = Math.random();
while(this.registeredIds.has(id)) {
id = Math.random();
}
registeredIds.add(id);
return id;
}
generate(10)
crypto.randomUUID()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
generate | |
crypto.randomUUID() |
Test name | Executions per second |
---|---|
generate | 2531979.2 Ops/sec |
crypto.randomUUID() | 801178.8 Ops/sec |
The provided benchmark focuses on generating random identifiers using two different methods: a custom function (generate
) and the built-in JavaScript method (crypto.randomUUID()
).
Custom Function (generate
):
Math.random()
. It maintains a Set
called registeredIds
to ensure that generated IDs are unique. If a randomly generated ID already exists in the Set
, it generates a new ID until it finds a unique one.Math.random()
can provide, which may not be suitable for all security contexts.Built-in Method (crypto.randomUUID()
):
The benchmark results indicate the number of executions per second for each method:
generate()
function yielded approximately 2,531,979 executions per second, which demonstrates high performance under the tested condition.crypto.randomUUID()
method yielded around 801,178 executions per second, which is significantly lower in comparison.Use Cases: The choice between using a custom solution like generate
or the standard library method crypto.randomUUID()
largely depends on the specific requirements of the application. For most scenarios where average randomness is acceptable and you are generating a few IDs, the custom method might be sufficient. However, for applications requiring high security and uniqueness guarantees (e.g., user sessions, transaction IDs), crypto.randomUUID()
is the better choice.
Alternatives: Other alternatives for generating unique identifiers in JavaScript could include:
In summary, this benchmark evaluates two methods of generating random identifiers, showcasing a trade-off between performance, security, and customizability, depending on the selected approach.