This content originally appeared on DEV Community and was authored by Nikita Galkin
Node.js v14.17 release added crypto.randomUUID()
. This method allows to generate random RFC 4122 Version 4 UUID strings. Example:
const { randomUUID } = require('crypto');
console.log(randomUUID());
// '43c98ac2-8493-49b0-95d8-de843d90e6ca'
I wondered how big the difference between uuid generation by Node.js API and uuid package.
For benchmarking I prefer to use hyperfine. It is like apache benchmark, but for CLI commands. There are have two cases:
- require('crypto').randomUUID()
- require('uuid').v4()
Let's put them into two files:
// test-native.js
const { randomUUID } = require('crypto');
for (let i = 0; i < 10_000_000; i++) {
randomUUID();
}
// test-uuid.js
const { v4 } = require('uuid');
for (let i = 0; i < 10_000_000; i++) {
v4();
}
Now we ready for benchmarking:
hyperfine 'node test-native.js' 'node test-uuid.js'
This command shows that native generation is three times faster than uuid
package. Awesome!
This content originally appeared on DEV Community and was authored by Nikita Galkin

Nikita Galkin | Sciencx (2021-05-19T00:36:30+00:00) crypto.randomUUID is three times faster uuid.v4. Retrieved from https://www.scien.cx/2021/05/19/crypto-randomuuid-is-three-times-faster-uuid-v4/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.