Add crypto API randomInt() to random benchmarks
[benchmarks-js.git] / random.js
index f4fd9f0bd53f9182f13541be0b3bb17bc7c5e27c..2bdd430aea2ad7461772e1592c94d8c3ad3ceafa 100644 (file)
--- a/random.js
+++ b/random.js
@@ -1,7 +1,11 @@
 const Benchmark = require('benny')
-const { secureRandom } = require('./benchmark-utils')
+const {
+  secureRandom,
+  secureRandomWithRandomValues
+} = require('./benchmark-utils')
+const crypto = require('crypto')
 
-const maximum = Number.MAX_SAFE_INTEGER
+const maximum = 281474976710655
 
 /**
  * @param max
@@ -20,6 +24,26 @@ function getSecureRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) {
   return Math.floor(secureRandom() * (max + 1))
 }
 
+/**
+ * @param max
+ * @param min
+ * @returns
+ */
+function getSecureRandomIntegerWithRandomValues (
+  max = Number.MAX_SAFE_INTEGER,
+  min = 0
+) {
+  if (max < min || max < 0 || min < 0) {
+    throw new RangeError('Invalid interval')
+  }
+  max = Math.floor(max)
+  if (min != null && min !== 0) {
+    min = Math.ceil(min)
+    return Math.floor(secureRandomWithRandomValues() * (max - min + 1)) + min
+  }
+  return Math.floor(secureRandomWithRandomValues() * (max + 1))
+}
+
 /**
  * @param max
  * @param min
@@ -42,7 +66,16 @@ Benchmark.suite(
   Benchmark.add('Secure random integer generator', () => {
     getSecureRandomInteger(maximum)
   }),
-  Benchmark.add('Random integer generator', () => {
+  Benchmark.add(
+    'Secure random with getRandomValues() integer generator',
+    () => {
+      getSecureRandomIntegerWithRandomValues(maximum)
+    }
+  ),
+  Benchmark.add('Crypto random integer generator', () => {
+    crypto.randomInt(maximum)
+  }),
+  Benchmark.add('Math random integer generator', () => {
     getRandomInteger(maximum)
   }),
   Benchmark.cycle(),