Skip to content
Myr

Port amazing nope-id optimizations (#602)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Port amazing nope-id optimizations * Update benchmark

authored by Andrey Sitnik · committed by GitHub · parent a83bf65 · Browse files · 11 files+303 added−160 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

11 files+303 added−160 removed

  • tests:+83 added−8 removed
  • other:+220 added−152 removed

11 files+303 added−160 removed

modified:test/benchmark.js+8 added-8 removed
modified:test/index.test.js+75 added
1import { equal, match, notEqual, ok, throws } from 'node:assert'2import { webcrypto } from 'node:crypto'3import { after, before, describe, test } from 'node:test'45import * as browser from '../index.browser.js'6import * as node from '../index.js'
49 unmodified lines
56 match(urlAlphabet, new RegExp(char, 'g'))57 }58 })5960 test(`generates IDs bigger than pool size`, () => {61 let id = nanoid(70000)62 equal(id.length, 70000)63 for (let char of id) {64 match(urlAlphabet, new RegExp(char, 'g'))65 }66 })6768 test(`accepts string`, () => {69 equal(nanoid('10').length, 10)70 })71
80 unmodified lines
152 let id1 = nanoid()153 let id2 = nanoid(makeProxyNumberToReproducePreviousID())154 notEqual(id1, id2)155 })156157 test(`recovers from crypto errors`, () => {158 nanoid(1)159 let original = webcrypto.getRandomValues160 webcrypto.getRandomValues = () => {161 throw new Error('Entropy failure')162 }163 try {164 throws(() => {165 nanoid(65536)166 }, /Entropy failure/)167 throws(() => {168 random(131072)169 }, /Entropy failure/)170 } finally {171 webcrypto.getRandomValues = original172 }173 equal(nanoid().length, 21)174 equal(random(10).length, 10)175 })176 }177178 describe('customAlphabet', () => {179 test(`has options`, () => {
48 unmodified lines
228 let third = nanoid2()229 notEqual(second, third)230 })231232 test(`supports multi-byte characters`, () => {233 let ALPHABET = 'абвгд'234 let nanoid2 = customAlphabet(ALPHABET, 10)235 for (let i = 0; i < 100; i++) {236 let id = nanoid2()237 equal(id.length, 10)238 for (let char of id) {239 ok(ALPHABET.includes(char))240 }241 }242 })243244 test(`supports alphabets bigger than 256 symbols`, () => {245 equal(customAlphabet('a'.repeat(300))(0), '')246 })247248 test(`supports non-string alphabets`, () => {249 let ALPHABET = ['a', 'b', 'c', 'd']250 let nanoid2 = customAlphabet(ALPHABET, 10)251 let id = nanoid2()252 equal(id.length, 10)253 for (let char of id) {254 ok(ALPHABET.includes(char))255 }256 })257258 if (type === 'node') {259 test(`does not fall in infinite loop`, () => {260 equal(customAlphabet('abc')(0), '')261 equal(customAlphabet('abc', 0)(0), '')
21 unmodified lines
283 let nanoid0 = customRandom('abc', 5, size => new Uint8Array(size))284 equal(nanoid0(0), '')285 equal(customRandom('', 5, size => new Uint8Array(size))(0), '')286 })287288 test(`supports power-of-two alphabets`, () => {289 let sequence = [2, 255, 3, 7]290 function fakeRandom(size) {291 let bytes = []292 for (let i = 0; i < size; i += sequence.length) {293 bytes = bytes.concat(sequence.slice(0, size - i))294 }295 return bytes296 }297 let nanoid4 = customRandom('abcd', 4, fakeRandom)298 equal(nanoid4(), 'dddc')299 equal(nanoid4(0), '')300 })301 })302303 describe('urlAlphabet', () => {304 test(`is string`, () => {
11 unmodified lines
316 })317 })318319 describe('random', () => {320 test(`throws on negative size`, () => {321 throws(() => {322 random(-1)323 }, /Wrong ID size|Invalid typed array length/)324 })325326 test(`generates small random buffers`, () => {327 for (let i = 0; i < urlAlphabet.length; i++) {328 equal(random(10).length, 10)329 }
17 unmodified lines
modified:index.d.ts+2 added-2 removed
modified:index.js+106 added-41 removed
1import { webcrypto as crypto } from 'node:crypto'23import { urlAlphabet as scopedUrlAlphabet } from './url-alphabet/index.js'3import { urlAlphabet } from './url-alphabet/index.js'45export { urlAlphabet } from './url-alphabet/index.js'5export { urlAlphabet }67// It is best to make fewer, larger requests to the crypto module to8// avoid system call overhead. So, random numbers are generated in a9// pool. The pool is a Buffer that is larger than the initial random10// request size by this multiplier. The pool is enlarged if subsequent11// requests exceed the maximum buffer size.12const POOL_SIZE_MULTIPLIER = 12813let pool, poolOffset7// `crypto.getRandomValues` rejects requests over 65536 bytes,8// so bigger buffers are filled by chunks.9const GET_RANDOM_LIMIT = 655361015function fillPool(bytes) {16 if (bytes < 0) throw new RangeError('Wrong ID size')17 try {18 if (!pool || pool.length < bytes) {19 pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)20 crypto.getRandomValues(pool)21 poolOffset = 022 } else if (poolOffset + bytes > pool.length) {23 crypto.getRandomValues(pool)24 poolOffset = 025 }26 } catch (e) {27 pool = undefined28 throw e11function fillRandom(buffer) {12 let from = 013 while (from < buffer.length) {14 let to = Math.min(from + GET_RANDOM_LIMIT, buffer.length)15 crypto.getRandomValues(buffer.subarray(from, to))16 from = to17 }30 poolOffset += bytes18}1920export function random(bytes) {21 // `|=` convert `bytes` to number to prevent `valueOf` abusing35 // and pool pollution36 fillPool((bytes |= 0))37 return pool.subarray(poolOffset - bytes, poolOffset)22 bytes |= 023 if (bytes < 0) throw new RangeError('Wrong ID size')24 // `random()` is used rarely and not in hot paths, so it makes25 // a direct crypto call instead of using a byte pool.26 let buffer = Buffer.allocUnsafe(bytes)27 fillRandom(buffer)28 return buffer29}3031export function customRandom(alphabet, defaultSize, getRandom) {32 // Random bytes are 0-255. `random % alphabet.length` can waste
54 unmodified lines
87 }88 }89}90100export function customAlphabet(alphabet, size = 21) {101 return customRandom(alphabet, size, random)102}91// The string pool optimizations in `customAlphabet()` and `nanoid()`92// were ported from the nope-id project by Orhan Aydoğdu:93// https://github.com/orhanayd/nope-id94104export function nanoid(size = 21) {105 // `|=` convert `size` to number to prevent `valueOf` abusing106 // and pool pollution107 fillPool((size |= 0))95// Maximum size of the pre-generated string pool in `customAlphabet()`.96const POOL_MAX = GET_RANDOM_LIMIT / 297109 let id = ''110 // We are reading directly from the random pool to avoid creating new array111 for (let i = poolOffset - size; i < poolOffset; i++) {112 // The following mask reduces the random byte in the 0-255 value113 // range to the 0-63 value range.114 id += scopedUrlAlphabet[pool[i] & 63]98export function customAlphabet(alphabet, defaultSize = 21) {99 if (100 typeof alphabet !== 'string' ||101 !alphabet.length ||102 alphabet.length > 256103 ) {104 return customRandom(alphabet, defaultSize, random)105 }116 return id106 for (let i = 0; i < alphabet.length; i++) {107 if (alphabet.charCodeAt(i) > 255) {108 // The fast path below writes char codes to a byte buffer,109 // so it supports only single-byte characters.110 return customRandom(alphabet, defaultSize, random)111 }112 }113114 // Alphabet char codes to write IDs into a byte buffer directly.115 let charCodes = Uint8Array.from(alphabet, str => {116 return str.charCodeAt(0)117 })118 let alphabetLen = alphabet.length119 // The smallest `2^n - 1` covering all alphabet indexes. Rejecting120 // `byte & mask >= alphabetLen` avoids modulo bias without `%` operation.121 let mask = (2 << (31 - Math.clz32((alphabetLen - 1) | 1))) - 1122123 // IDs are pre-generated into a string pool: accepted alphabet chars are124 // written to a byte buffer, converted to a string with one125 // `Buffer#toString()` call, and every ID is a cheap `String#substring()`.126 // It avoids per-character string concatenations and pays string127 // allocation cost once per refill.128 //129 // The pool starts at the first requested size and grows geometrically,130 // so short-living generators do not pay for a full pool.131 let pool = ''132 let poolOffset = 0133 let poolNext = 0134135 return (size = defaultSize) => {136 // `|=` convert `size` to number to prevent `valueOf` abusing137 // and pool offset pollution138 size |= 0139 if (size < 0) throw new RangeError('Wrong ID size')140 if (size === 0) return ''141 if (poolOffset + size > pool.length) {142 let target = Math.max(poolNext, size)143 poolNext = Math.min(target * 16, POOL_MAX)144 let buffer = Buffer.allocUnsafe(target)145 if (mask === alphabetLen - 1) {146 // Power-of-two alphabets like `urlAlphabet` accept every byte,147 // so random bytes are translated in place without rejections.148 fillRandom(buffer)149 for (let i = 0; i < target; i++) {150 buffer[i] = charCodes[buffer[i] & mask]151 }152 } else {153 // Rejection sampling accepts `alphabetLen` of every `mask + 1`154 // random bytes. `1.6` requests extra bytes to cover155 // unlucky streaks in most fills.156 let randomBytes = Buffer.allocUnsafe(157 Math.ceil((1.6 * (mask + 1) * target) / alphabetLen)158 )159 let accepted = 0160 while (accepted < target) {161 fillRandom(randomBytes)162 for (let i = 0; i < randomBytes.length; i++) {163 let index = randomBytes[i] & mask164 if (index < alphabetLen) {165 buffer[accepted++] = charCodes[index]166 if (accepted === target) break167 }168 }169 }170 }171 pool = buffer.toString('latin1')172 poolOffset = 0173 }174 poolOffset += size175 return pool.substring(poolOffset - size, poolOffset)176 }177}178179// `nanoid()` reuses the `customAlphabet()` string pool logic.180// The URL-safe alphabet has 64 symbols, so the generator translates181// random bytes in place without rejections.182export const nanoid = customAlphabet(urlAlphabet)
modified:README.ar.md+16 added-16 removed
12 unmodified lines
13> والتي يستحيل ألّا تحظى بالاحترام."1415- **صغير الحجم.** 118 بايت فقط (بعد التصغير والضغط ببروتلي). بدون أيّ اعتماديات خارجية.16 يتم التحكّم بالحجم عبر [Size Limit].17- **سريع.** أسرع بنسبة 50% من `crypto.randomUUID()` الأصلية.18- **آمن.** يستخدم مُولِّد أرقام عشوائية على مستوى العتاد. يمكن استخدامه في بيئات الكلستر.19- **مُعرِّفات قصيرة.** يستخدم أبجدية أكبر من UUID وهي (`A-Za-z0-9_-`).20 لذا تم تقليص حجم المُعرِّف من 36 إلى 21 رمزًا.21- **قابل للنقل.** تم نقل Nano ID
55 unmodified lines
77يوجد اختلافان رئيسيان بين Nano ID و UUID v4:78791. يستخدم Nano ID أبجدية أكبر، لذا يتم ضغط عدد مماثل من البتّات العشوائية80 في 21 رمزًا فقط بدلاً من 36.802. كود Nano ID أصغر بـ **4 مرات** من حزمة `uuid/v4`:81 118 بايت مقابل 423.812. Nano ID أسرع من `crypto.randomUUID` و`uuid/v4`.8283## اختبار الأداء8485</div>8687```rust88$ node ./test/benchmark.js89nope-id 27,398,074 ops/sec90crypto.randomUUID 14,055,107 ops/sec91uuid v4 9,256,301 ops/sec92@napi-rs/uuid 7,100,180 ops/sec93uid/secure 7,312,765 ops/sec94@lukeed/uuid 5,543,254 ops/sec95nanoid 4,954,561 ops/sec96customAlphabet 6,708,339 ops/sec97nanoid for browser 497,980 ops/sec98secure-random-string 412,049 ops/sec99uid-safe.sync 420,669 ops/sec89nope-id 20,386,830 ops/sec90nanoid 20,434,827 ops/sec91customAlphabet 20,544,476 ops/sec92crypto.randomUUID 12,865,759 ops/sec93uuid v4 7,930,104 ops/sec94@napi-rs/uuid 5,573,171 ops/sec95uid/secure 6,308,267 ops/sec96@lukeed/uuid 5,278,597 ops/sec97nanoid for browser 311,497 ops/sec98secure-random-string 301,667 ops/sec99uid-safe.sync 297,815 ops/sec100101Non-secure:102uid 27,106,859 ops/sec103nanoid/non-secure 2,672,540 ops/sec104rndm 2,666,518 ops/sec102uid 20,286,757 ops/sec103nanoid/non-secure 2,397,594 ops/sec104rndm 2,445,462 ops/sec105```106107<div dir="rtl">108
479 unmodified lines
modified:README.id-ID.md+16 added-15 removed
9 unmodified lines
10> "Sebuah tingkat kesempurnaan yang luar biasa,11> yang mana tidak mungkin untuk tidak dihormati."1213- **Ringan.** Hanya 118 bytes (diperkecil dan brotlied). Tidak ada ketergantungan (dependencies) apapun. [Size Limit](https://github.com/ai/size-limit) mengatur ukuran dari generator ini.14- **Cepat.** 50% lebih cepat ketimbang `crypto.randomUUID()` bawaan.15- **Aman.** Nano ID menggunakan RNG yang terdapat pada perangkat keras. Dapat digunakan dalam lingkungan seperti klaster.16- **ID yang pendek.** Nano ID menggunakan alfabet yang lebih banyak ketimbang UUID (`A-Za-z0-9_-`), karenanya ukuran ID menjadi berkurang dari 36 menjadi 21 simbol.17- **Portabel.** Nano ID telah dimigrasi untuk [20 bahasa pemrograman lainnya](#bahasa-pemrograman-lainnya).18
39 unmodified lines
5859Ada dua buah perbedaan antara Nano ID dan UUID v4:60611. Nano ID menggunakan alfabet yang lebih lebar, karenanya jumlah bita acak dapat 'dikemas' dalam 21 simbol, bukan 36 simbol.612. Kode sumber Nano ID **empat kali lebih kecil** ketimbang `uuid/v4`: 118 bytes dibanding 423 bytes.622. Nano ID lebih cepat ketimbang `crypto.randomUUID` dan `uuid/v4`.6364## Benchmark6566```rust67$ node ./test/benchmark.js67nope-id 27,398,074 ops/sec68crypto.randomUUID 14,055,107 ops/sec69uuid v4 9,256,301 ops/sec70@napi-rs/uuid 7,100,180 ops/sec71uid/secure 7,312,765 ops/sec72@lukeed/uuid 5,543,254 ops/sec73nanoid 4,954,561 ops/sec74customAlphabet 6,708,339 ops/sec75nanoid for browser 497,980 ops/sec76secure-random-string 412,049 ops/sec77uid-safe.sync 420,669 ops/sec68nope-id 20,386,830 ops/sec69nanoid 20,434,827 ops/sec70customAlphabet 20,544,476 ops/sec71crypto.randomUUID 12,865,759 ops/sec72uuid v4 7,930,104 ops/sec73@napi-rs/uuid 5,573,171 ops/sec74uid/secure 6,308,267 ops/sec75@lukeed/uuid 5,278,597 ops/sec76nanoid for browser 311,497 ops/sec77secure-random-string 301,667 ops/sec78uid-safe.sync 297,815 ops/sec7980Non-secure:80uid 27,106,859 ops/sec81nanoid/non-secure 2,672,540 ops/sec82rndm 2,666,518 ops/sec81uid 20,286,757 ops/sec82nanoid/non-secure 2,397,594 ops/sec83rndm 2,445,462 ops/sec84```8586Konfigurasi pengujian: Framework 13 7840U, Fedora 39, Node.js 21.6.87
258 unmodified lines
modified:README.ja.md+16 added-16 removed
10 unmodified lines
11> これは尊敬せざるを得ない。」1213- **小さい。** 118バイト(圧縮・brotli圧縮後)。依存関係なし。14 [Size Limit]がサイズを管理。15- **高速。** ネイティブの`crypto.randomUUID()`より50%高速。16- **安全。** ハードウェア乱数生成器を使用。クラスタでも利用可能。17- **短いID。** UUIDより大きなアルファベット(A-Za-z0-9\_-)を使用。18 そのためID長は36から21文字に短縮されています。19- **移植性。** Nano IDは[20以上のプログラミング言語](./README.md#other-programming-languages)に移植されています。
50 unmodified lines
70Nano IDとUUID v4の主な違いは2つあります:71721. Nano IDはより大きなアルファベットを使用するため、同様のランダムビット数が73 36文字ではなく21文字に詰め込まれています。732. Nano IDのコードはuuid/v4パッケージより**4倍小さい**です:74 423バイトではなく118バイトです。742. Nano IDは`crypto.randomUUID`や`uuid/v4`よりも高速です。7576## ベンチマーク7778```rust79$ node ./test/benchmark.js80nope-id 27,398,074 ops/sec81crypto.randomUUID 14,055,107 ops/sec82uuid v4 9,256,301 ops/sec83@napi-rs/uuid 7,100,180 ops/sec84uid/secure 7,312,765 ops/sec85@lukeed/uuid 5,543,254 ops/sec86nanoid 4,954,561 ops/sec87customAlphabet 6,708,339 ops/sec88nanoid for browser 497,980 ops/sec89secure-random-string 412,049 ops/sec90uid-safe.sync 420,669 ops/sec80nope-id 20,386,830 ops/sec81nanoid 20,434,827 ops/sec82customAlphabet 20,544,476 ops/sec83crypto.randomUUID 12,865,759 ops/sec84uuid v4 7,930,104 ops/sec85@napi-rs/uuid 5,573,171 ops/sec86uid/secure 6,308,267 ops/sec87@lukeed/uuid 5,278,597 ops/sec88nanoid for browser 311,497 ops/sec89secure-random-string 301,667 ops/sec90uid-safe.sync 297,815 ops/sec9192Non-secure:93uid 27,106,859 ops/sec94nanoid/non-secure 2,672,540 ops/sec95rndm 2,666,518 ops/sec93uid 20,286,757 ops/sec94nanoid/non-secure 2,397,594 ops/sec95rndm 2,445,462 ops/sec96```9798テスト構成:Framework 13 7840U, Fedora 39, Node.js 21.6.99
365 unmodified lines
modified:README.ko.md+16 added-16 removed
10 unmodified lines
11> 경의를 표하지 않을 수 없습니다”1213- **가볍습니다.** 118 bytes (minified 및 brotli 적용 후). 다른 의존성이 없습니다.14 [Size Limit] 의 기능으로 컨트롤합니다.15- **빠릅니다.** 네이티브 `crypto.randomUUID()` 보다 50% 더 빠릅니다.16- **안전합니다.** 하드웨어의 랜덤 생성기를 사용합니다. 클러스터에서 사용할 수 있습니다.17- **짧은 ID를 생성합니다.** UUID와는 다르게 대소문자를 모두 사용하여 키를 생성하므로, 36 byte를 차지하는 UUID와 다르게 21 byte만으로도 고유 아이디를 생성할 수 있습니다.18 So ID size was reduced from 36 to 21 symbols.19- **이식이 쉽습니다.** Nano ID 는 20개 이상의 언어로 포팅되었습니다 [다른 언어들](#다른-언어들).
49 unmodified lines
6970Nano ID와 UUID v4에는 두 가지의 주요한 차이점이 있습니다:71721. Nano ID는 대문자를 사용합니다. 그래서 유사한 개수의 랜덤 값을 36개가 아닌 21개의 문자로 나타낼 수 있습니다.722. Nano ID 코드는 `uuid/v4` 패키지보다 **4분의 1 사이즈**입니다:73 UUIDv4는 423 bytes, Nano ID는 118 bytes 입니다.732. Nano ID는 `crypto.randomUUID` 및 `uuid/v4` 보다 빠릅니다.7475## 벤치마크7677```rust78$ node ./test/benchmark.js79nope-id 27,398,074 ops/sec80crypto.randomUUID 14,055,107 ops/sec81uuid v4 9,256,301 ops/sec82@napi-rs/uuid 7,100,180 ops/sec83uid/secure 7,312,765 ops/sec84@lukeed/uuid 5,543,254 ops/sec85nanoid 4,954,561 ops/sec86customAlphabet 6,708,339 ops/sec87nanoid for browser 497,980 ops/sec88secure-random-string 412,049 ops/sec89uid-safe.sync 420,669 ops/sec79nope-id 20,386,830 ops/sec80nanoid 20,434,827 ops/sec81customAlphabet 20,544,476 ops/sec82crypto.randomUUID 12,865,759 ops/sec83uuid v4 7,930,104 ops/sec84@napi-rs/uuid 5,573,171 ops/sec85uid/secure 6,308,267 ops/sec86@lukeed/uuid 5,278,597 ops/sec87nanoid for browser 311,497 ops/sec88secure-random-string 301,667 ops/sec89uid-safe.sync 297,815 ops/sec9091Non-secure:92uid 27,106,859 ops/sec93nanoid/non-secure 2,672,540 ops/sec94rndm 2,666,518 ops/sec92uid 20,286,757 ops/sec93nanoid/non-secure 2,397,594 ops/sec94rndm 2,445,462 ops/sec95```9697테스트 환경: 프레임워크 13 7840U, 페도라 39, Node.js 21.6.98
370 unmodified lines
modified:README.md+16 added-16 removed
10 unmodified lines
11> which is simply impossible not to respect.”1213- **Small.** 118 bytes (minified and brotlied). No dependencies.14 [Size Limit] controls the size.15- **Fast.** 50% faster than native `crypto.randomUUID()`.16- **Safe.** It uses hardware random generator. Can be used in clusters.17- **Short IDs.** It uses a larger alphabet than UUID (`A-Za-z0-9_-`).18 So ID size was reduced from 36 to 21 symbols.19- **Portable.** Nano ID was ported
51 unmodified lines
71There are two main differences between Nano ID and UUID v4:72731. Nano ID uses a bigger alphabet, so a similar number of random bits74 are packed in just 21 symbols instead of 36.742. Nano ID code is **4 times smaller** than `uuid/v4` package:75 118 bytes instead of 423.752. Nano ID is faster than `crypto.randomUUID` and `uuid/v4`.7677## Benchmark7879```rust80$ node ./test/benchmark.js81nope-id 27,398,074 ops/sec82crypto.randomUUID 14,055,107 ops/sec83uuid v4 9,256,301 ops/sec84@napi-rs/uuid 7,100,180 ops/sec85uid/secure 7,312,765 ops/sec86@lukeed/uuid 5,543,254 ops/sec87nanoid 4,954,561 ops/sec88customAlphabet 6,708,339 ops/sec89nanoid for browser 497,980 ops/sec90secure-random-string 412,049 ops/sec91uid-safe.sync 420,669 ops/sec81nope-id 20,386,830 ops/sec82nanoid 20,434,827 ops/sec83customAlphabet 20,544,476 ops/sec84crypto.randomUUID 12,865,759 ops/sec85uuid v4 7,930,104 ops/sec86@napi-rs/uuid 5,573,171 ops/sec87uid/secure 6,308,267 ops/sec88@lukeed/uuid 5,278,597 ops/sec89nanoid for browser 311,497 ops/sec90secure-random-string 301,667 ops/sec91uid-safe.sync 297,815 ops/sec9293Non-secure:94uid 27,106,859 ops/sec95nanoid/non-secure 2,672,540 ops/sec96rndm 2,666,518 ops/sec94uid 20,286,757 ops/sec95nanoid/non-secure 2,397,594 ops/sec96rndm 2,445,462 ops/sec97```9899Test configuration: Framework 13 7840U, Fedora 39, Node.js 21.6.100
384 unmodified lines
modified:README.ru.md+16 added-15 removed
11 unmodified lines
12> который просто невозможно не уважать»1314- **Лёгкий.** 118 байт (после минификации и Brotli). Без зависимостей.15 [Size Limit] следит за размером.16- **Быстрый.** На 50% быстрее нативного `crypto.randomUUID()`.17- **Безопасный.** Использует аппаратный генератор случайных чисел.18 Можно использовать в кластерах машин.19- **Короткие ID.** Используется больший алфавит, чем у UUID (`A-Za-z0-9_-`).20 Поэтому длина ID уменьшена с 36 до 21 символа.
56 unmodified lines
77781. Nano ID использует более широкий алфавит, и сравнимое количество79 битов случайности будут упакованы в более короткую строку80 (21 символ, против 36 у UUID).802. Код Nano ID **в 4 раз меньше**, чем у `uuid/v4` — 118 байт против 423.812. Nano ID быстрее, чем `crypto.randomUUID` и `uuid/v4`.8283## Сравнение производительности8485```rust86$ node ./test/benchmark.js86nope-id 27,398,074 ops/sec87crypto.randomUUID 14,055,107 ops/sec88uuid v4 9,256,301 ops/sec89@napi-rs/uuid 7,100,180 ops/sec90uid/secure 7,312,765 ops/sec91@lukeed/uuid 5,543,254 ops/sec92nanoid 4,954,561 ops/sec93customAlphabet 6,708,339 ops/sec94nanoid for browser 497,980 ops/sec95secure-random-string 412,049 ops/sec96uid-safe.sync 420,669 ops/sec87nope-id 20,386,830 ops/sec88nanoid 20,434,827 ops/sec89customAlphabet 20,544,476 ops/sec90crypto.randomUUID 12,865,759 ops/sec91uuid v4 7,930,104 ops/sec92@napi-rs/uuid 5,573,171 ops/sec93uid/secure 6,308,267 ops/sec94@lukeed/uuid 5,278,597 ops/sec95nanoid for browser 311,497 ops/sec96secure-random-string 301,667 ops/sec97uid-safe.sync 297,815 ops/sec9899Non-secure:99uid 27,106,859 ops/sec100nanoid/non-secure 2,672,540 ops/sec101rndm 2,666,518 ops/sec100uid 20,286,757 ops/sec101nanoid/non-secure 2,397,594 ops/sec102rndm 2,445,462 ops/sec103```104105Среда сравнения: Framework 13 7840U, Fedora 39, Node.js 21.6.106
359 unmodified lines
modified:README.zh-CN.md+16 added-15 removed
8 unmodified lines
910> “一个惊人的无意义的完美主义水平,这简直让人无法不敬佩。”1112- **小巧.** 118字节 (经过压缩和Brotli处理)。没有依赖。[Size Limit] 控制大小。13- **快速.** 比原生 `crypto.randomUUID()` 快 50%。14- **安全.** 它使用硬件随机生成器。可在集群中使用。15- **紧凑.** 它使用比 UUID(`A-Za-z0-9_-`)更大的字母表。因此,ID 大小从36个符号减少到21个符号。16- **可移植.** Nano ID 已被移植到 [20种编程语言](#其他编程语言)。17
47 unmodified lines
65Nano ID 和 UUID v4之间有两个主要区别:66671. Nano ID 使用更大的字母表,所以类似数量的随机位68 被包装在21个符号中,而不是36个。682. Nano ID 代码比 `uuid/v4` 包少 **4倍**: 118字节而不是423字节.692. Nano ID 比 `crypto.randomUUID` 和 `uuid/v4` 更快。7071## 基准值7273```rust74$ node ./test/benchmark.js74nope-id 27,398,074 ops/sec75crypto.randomUUID 14,055,107 ops/sec76uuid v4 9,256,301 ops/sec77@napi-rs/uuid 7,100,180 ops/sec78uid/secure 7,312,765 ops/sec79@lukeed/uuid 5,543,254 ops/sec80nanoid 4,954,561 ops/sec81customAlphabet 6,708,339 ops/sec82nanoid for browser 497,980 ops/sec83secure-random-string 412,049 ops/sec84uid-safe.sync 420,669 ops/sec75nope-id 20,386,830 ops/sec76nanoid 20,434,827 ops/sec77customAlphabet 20,544,476 ops/sec78crypto.randomUUID 12,865,759 ops/sec79uuid v4 7,930,104 ops/sec80@napi-rs/uuid 5,573,171 ops/sec81uid/secure 6,308,267 ops/sec82@lukeed/uuid 5,278,597 ops/sec83nanoid for browser 311,497 ops/sec84secure-random-string 301,667 ops/sec85uid-safe.sync 297,815 ops/sec8687Non-secure:87uid 27,106,859 ops/sec88nanoid/non-secure 2,672,540 ops/sec89rndm 2,666,518 ops/sec88uid 20,286,757 ops/sec89nanoid/non-secure 2,397,594 ops/sec90rndm 2,445,462 ops/sec91```9293测试配置: Framework 13 7840U, Fedora 39, Node.js 21.6.94
321 unmodified lines