Crypto functions: Deno v/s Node performance series
Deno supports crypto functions by implementing web’s crypto APIs. At the time of writing (Deno v1.11.x), there is a small set of crypto functions available: randomUUID, getRandomValues, subtle.digest. However, the number increases with every release. A follow-up article will be published when the Deno crypto API increases the functionality.
In this article, we’ll find out how Deno’s crypto functions perform in comparison to Node.js.
randomUUID
This synchronous function generates a V4 UUID. The usage is same in Deno and Node.js.
//Deno
crypto.randomUUID();//Node.js
const crypto=require('crypto');
crypto.randomUUID();
Here is the comparison of performance for 100K, 500K, and 1M sequential calls to the function:
What? Node.js is way way faster than Deno! Why?
The reason being that, to improve performance, Node.js generates & caches enough random data to generate up to 128 random UUIDs. The performance optimization is enabled by default. It can be turned off by setting: disableEntropyCache to true. There is no such performance optimization in Deno.
Here is the comparison of performance for 100K, 500K, and 1M sequential calls to the function with no performance optimization:
Without caching, Node.js is slower than Deno.
But why would we disable cache? Perhaps Deno can implement some similar optimization.
randomUUID in Node.js is much faster than Deno
getRandomValues
The getRandomValues function is used to fill a typed array with cryptographically strong random numbers. We’ll look at the common use cases: Uint8Array, Uint16Array, and Uint32Array. In each call of the function, an array of 100 elements is filled.
//Deno
const d=new Uint8Array(100);
crypto.getRandomValues(d);//Node.js
const { getRandomValues } = require('crypto').webcrypto;const d=new Uint8Array(100);
getRandomValues(d);
Here is the comparison of performance for 100K, 500K, and 1M sequential calls to the function (Remember that in each call, we fill an array with 100 elements):
Uint8Array
Uint16Array
Uint32Array
getRandomValues in Deno is much faster than Node.js
The time taken is the same regardless of the type of input
Digest
Crypto’s subtle.digest is used in calculating SHA-1, SHA-256, SHA-384, and SHA-512 for a data.
//random data
const d=Uint8Array.from({length: 1000}, () => Math.floor(Math.random() * 1000));//Deno
await crypto.subtle.digest('SHA-1', d);//Node.js
const { subtle } = require('crypto').webcrypto;
await crypto.subtle.digest('SHA-1', d);
Here is the comparison of performance for 100K, 500K, and 1M sequential calls to the function:
SHA-1
SHA-256
SHA-384
SHA-512
Subtle.digest in Node.js is a bit faster than Deno
The time taken is the same regardless of the algorithm
This story is a part of the exclusive medium publication on Deno: Deno World.