Skip to content

Commit

Permalink
3x speed up ID generation
Browse files Browse the repository at this point in the history
  • Loading branch information
ai committed Aug 6, 2017
1 parent 486009f commit 17b274e
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
2 changes: 2 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@ coverage/

.yaspellerrc
docs/

benchmark
13 changes: 13 additions & 0 deletions benchmark
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#!/usr/bin/env node

var nanoid = require('./')
var generate = require('./generate')

var start = Date.now()
for (var i = 0; i < 100000; i++) {
nanoid()
generate('1234567890abcdef', 10)
}
var end = Date.now()

process.stdout.write(end - start + ' ms\n')
5 changes: 4 additions & 1 deletion format.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,12 @@
* @name format
*/
module.exports = function (random, alphabet, size) {
var step = Math.ceil(1.2 * 256 / alphabet.length * size)

var bytes, byte
var id = ''
while (id.length !== size) {
bytes = random(size)
bytes = random(step)
for (var i = 0; i < bytes.length; i++) {
byte = bytes[i]
if (byte < alphabet.length) {
Expand All @@ -36,6 +38,7 @@ module.exports = function (random, alphabet, size) {
}
}
}

return id
}

Expand Down

0 comments on commit 17b274e

Please sign in to comment.