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!
Top comments (7)
Actually, the
randomUUID
in Node v15.12+/v16 is a little more optimized, and outperforms it even more :)It seems the faster
crypto.randomUUID
is, the sloweruuid.js
runs on that version :DThank you!
This package is depreciated. Use
uuid
instead.J
I didn't get all fancy with hyperfine, but a cursory test shows no appreciable difference in performance with npmjs.com/package/uuid. Still, 2 less dependencies is nice. :)
Just curious,
Is the difference any noticeable generating a single UUID or several hundred UUIDs as opposed to millions?
No. You likely won't notice much of a difference at all with a low number of uses in your code.
The good news is that the API is the same, so it's a simple function import swap, especially if you rename the function on import like: