Skip to content

Instantly share code, notes, and snippets.

@andrewrk
Last active January 14, 2018 03:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewrk/9935b045c5d7d36f3e3c to your computer and use it in GitHub Desktop.
Save andrewrk/9935b045c5d7d36f3e3c to your computer and use it in GitHub Desktop.
faster, more random, and simpler than the node uuid module. 27 bytes of randomness instead of 16, yet still encoded into a string of length 32
var uuid1 = require('uuid');
var crypto = require('crypto');
testOne("uuid module", uuid1);
testOne("my code", uuid2);
function testOne(name, fn) {
process.stdout.write(name + ": ");
var start = new Date();
var s = "";
for (var i = 0; i < 1000000; i += 1) {
s += fn();
}
var end = new Date();
console.log((end - start) + "ms");
}
function uuid2() {
return rando(27).toString('base64');
}
function rando(size) {
try {
return crypto.randomBytes(size);
} catch (err) {
return crypto.pseudoRandomBytes(size);
}
}
$ node bench.js
uuid module: 4362ms
my code: 3202ms
browser: http://jsperf.com/random-string-vs-node-uuid
base64 version is a little slower, but it's also generating 11 more bytes of randomness than uuid v4.
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var crypto = window.crypto;
var arr = new Uint8Array(27);
function uuid() {
crypto.getRandomValues(arr);
var s = "";
for (var m = 0, t = 0; t < arr.length; m = (m + 1) % 4) {
var x;
if (m === 0) {
x = arr[t] >> 2;
t += 1;
} else if (m === 1) {
x = ((0x3 & arr[t-1]) << 4) | (arr[t] >> 4);
} else if (m === 2) {
x = ((0xf & arr[t]) << 2) | (arr[t+1] >> 6);
t += 1;
} else { // m === 3
x = arr[t] & 0x3f;
t += 1;
}
s += b64[x];
}
return s;
}
var crypto = require('crypto');
module.exports = uuid;
function uuid() {
return rando(27).toString('base64');
}
function rando(size) {
try {
return crypto.randomBytes(size);
} catch (err) {
return crypto.pseudoRandomBytes(size);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment