DEV Community

loading...
Cover image for crypto.randomUUID is three times faster uuid.v4

crypto.randomUUID is three times faster uuid.v4

Nikita Galkin
・1 min read

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'
Enter fullscreen mode Exit fullscreen mode

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:

  1. require('crypto').randomUUID()
  2. 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();
} 
Enter fullscreen mode Exit fullscreen mode
// test-uuid.js
const { v4 } = require('uuid');

for (let i = 0; i < 10_000_000; i++) {
  v4();
}
Enter fullscreen mode Exit fullscreen mode

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!

Discussion (3)

Collapse
rangoo94 profile image
Dawid Rusnak • Edited

Actually, the randomUUID in Node v15.12+/v16 is a little more optimized, and outperforms it even more :)

Benchmark #3: node-15 native.js
  Time (mean ± σ):     564.6 ms ±   5.5 ms    [User: 556.8 ms, System: 14.1 ms]
  Range (min … max):   559.6 ms … 575.2 ms    10 runs

Summary
  'node-15 native.js' ran
    1.01 ± 0.01 times faster than 'node-16 native.js'
    3.51 ± 0.09 times faster than 'node-14 native.js'
   11.18 ± 0.13 times faster than 'node-14 uuid.js'
   12.52 ± 0.14 times faster than 'node-16 uuid.js'
   12.65 ± 0.26 times faster than 'node-15 uuid.js'
Enter fullscreen mode Exit fullscreen mode
Collapse
qm3ster profile image
Mihail Malo

It seems the faster crypto.randomUUID is, the slower uuid.js runs on that version :D

Collapse
galkin profile image
Nikita Galkin Author

Thank you!