ai / nanoid

A tiny (124 bytes), secure, URL-friendly, unique string ID generator for JavaScript
https://zelark.github.io/nano-id-cc/
MIT License
24.22k stars 790 forks source link

Much faster implementation #466

Closed samuelgozi closed 6 months ago

samuelgozi commented 7 months ago

I know this is a lazy PR since I didn't check other files to make sure I'm making the correct changes, so I'm sorry about that. This implementation is much faster. The benchmark checks the time to generate one million nanoids.

$ node ./main.js
Old 1365ms
New 948ms

$ bun ./main.js
Old 462ms
New 138ms

I hope you find it useful 🙏

ai commented 7 months ago
  1. It is the file generated from index.browser.js. You need to fix it first.
  2. But browser's file should be tested in browsers. For Node/Bun we have another file index.js which has different optimizations.
samuelgozi commented 7 months ago

Tested on latest version:

Chrome

Old 1634ms
New 1245ms

Safari

Old 1208ms
New 760ms

Firefox

Old 1207ms
New 742ms

Browser support doesn't change at all. I will update the source file.

samuelgozi commented 7 months ago

I now updated the right place.

samuelgozi commented 7 months ago

Ok i will fix everything you mentioned. In regards to the use of the string inside the function, I don't think we should hoist it manually since I didn't see any effect on performance, but I do think that this way it looks nicer.

Maybe I should remove the comment instead since it not important

ai commented 7 months ago

OK, let's keep string as is. I will do some optimizations later for smaller bundle size.

samuelgozi commented 7 months ago

Done. Package size limit has exceeded by 34 B

ai commented 6 months ago

Package size limit has exceeded by 34 B

Try to import alphabet from https://github.com/ai/nanoid/blob/main/url-alphabet/index.js

We have a fun hack there, we put the same letters not in alhabetical order, but in order for better gzip.

And please update packge→size-limit for new size (so we will track size changes by commit).

samuelgozi commented 6 months ago

Package size limit has exceeded by 15 B TIL, very cool!

Made the changes

ai commented 6 months ago

I also reduced 8 bytes by reusing size variable 4db3464

samuelgozi commented 6 months ago

Using the while loop is actually a little bit faster. Very nice idea!