Skip to content

Commit

Permalink
Improve running time by about 15% by using strings & precomputed length.
Browse files Browse the repository at this point in the history
Strings are about 3-4% faster in my testing vs arrays. Surprisingly,
UIDCHARS.length is actually slightly faster than precomputing the length
outside the function - I assume reaching up the stack causes it.
  • Loading branch information
STRML committed Dec 15, 2014
1 parent a3b8def commit 3cfd2cc
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 6 deletions.
11 changes: 5 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
'use strict';
/**
* Module dependencies
*/
Expand All @@ -18,14 +19,13 @@ var UIDCHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_
* @api private
*/
function tostr(bytes) {
var chars, r, i;
var r = '', i;

r = [];
for (i = 0; i < bytes.length; i++) {
r.push(UIDCHARS[bytes[i] % UIDCHARS.length]);
r += UIDCHARS[bytes[i] % 64];
}

return r.join('');
return r;
}

/**
Expand All @@ -37,14 +37,13 @@ function tostr(bytes) {
*/

function uid(length, cb) {

if (typeof cb === 'undefined') {
return tostr(crypto.pseudoRandomBytes(length));
} else {
crypto.pseudoRandomBytes(length, function(err, bytes) {
if (err) return cb(err);
cb(null, tostr(bytes));
})
});
}
}

Expand Down
2 changes: 2 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ for (i = 0; i < chars.length; i++) {
}

console.log("Running", ITERATIONS, "iterations...");
console.time("Duration");

while(ITERATIONS--) {
var str = uid(LENGTH);
Expand All @@ -23,6 +24,7 @@ while(ITERATIONS--) {

console.log("Done. Distribution:");
console.log(JSON.stringify(freqs, undefined, 2));
console.timeEnd("Duration");

var vals = Object.keys(freqs).map(function(key) {
return freqs[key];
Expand Down

0 comments on commit 3cfd2cc

Please sign in to comment.