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
Provenance
- Commit
b1bb75f- Tree
c2b7f85- Author
Andrey Sitnik <andrey@sitnik.ru>- Committer
GitHub <noreply@github.com>- Parent
a83bf65
11 files changed+303 added−160 removed
modified:test/benchmark.js+8 added-8 removed
12 unmodified lines1314151617171819202122222324252627282930313233343536377 unmodified lines454647484344454647484950515236 unmodified lines12 unmodified linesimport { uid as uidSecure } from 'uid/secure'import { v4 as uuid4 } from 'uuid'
import { nanoid as browser } from '../index.browser.js'import { customAlphabet, nanoid } from '../index.js'import { nanoid, customAlphabet } from '../index.js'import { nanoid as nonSecure } from '../non-secure/index.js'
let bench = new Bench()
let nanoid2 = customAlphabet('1234567890abcdef-', 10)let nanoid2 = customAlphabet('1234567890abcdef-', 21)
bench .add('nope-id', () => { nopeid() }) .add('nanoid', () => { nanoid() }) .add('customAlphabet', () => { nanoid2() }) .add('crypto.randomUUID', () => { crypto.randomUUID() }) .add('uuid v4', () => {7 unmodified lines }) .add('@lukeed/uuid', () => { lukeed4() }) .add('nanoid', () => { nanoid() }) .add('customAlphabet', () => { nanoid2() }) .add('nanoid for browser', () => { browser() }) .add('secure-random-string', () => {36 unmodified linesmodified:test/index.test.js+75 added
1 import { equal, match, notEqual, ok, throws } from 'node:assert'2+import { webcrypto } from 'node:crypto'3 import { after, before, describe, test } from 'node:test'4 5 import * as browser from '../index.browser.js'6 import * as node from '../index.js'49 unmodified lines56 match(urlAlphabet, new RegExp(char, 'g'))57 }58 })59 60+ 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+ })67+68 test(`accepts string`, () => {69 equal(nanoid('10').length, 10)70 })71 80 unmodified lines152 let id1 = nanoid()153 let id2 = nanoid(makeProxyNumberToReproducePreviousID())154 notEqual(id1, id2)155 })156+157+ 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 }177 178 describe('customAlphabet', () => {179 test(`has options`, () => {48 unmodified lines228 let third = nanoid2()229 notEqual(second, third)230 })231 232+ 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+ })243+244+ test(`supports alphabets bigger than 256 symbols`, () => {245+ equal(customAlphabet('a'.repeat(300))(0), '')246+ })247+248+ 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+ })257+258 if (type === 'node') {259 test(`does not fall in infinite loop`, () => {260 equal(customAlphabet('abc')(0), '')261 equal(customAlphabet('abc', 0)(0), '')21 unmodified lines283 let nanoid0 = customRandom('abc', 5, size => new Uint8Array(size))284 equal(nanoid0(0), '')285 equal(customRandom('', 5, size => new Uint8Array(size))(0), '')286 })287+288+ 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 })302 303 describe('urlAlphabet', () => {304 test(`is string`, () => {11 unmodified lines316 })317 })318 319 describe('random', () => {320+ test(`throws on negative size`, () => {321+ throws(() => {322+ random(-1)323+ }, /Wrong ID size|Invalid typed array length/)324+ })325+326 test(`generates small random buffers`, () => {327 for (let i = 0; i < urlAlphabet.length; i++) {328 equal(random(10).length, 10)329 }17 unmodified linesmodified:index.d.ts+2 added-2 removed
68 unmodified lines69707172737374757677787980808182838422 unmodified lines68 unmodified lines * nanoid() //=> "fbaef" * ``` * * @param alphabet Alphabet used to generate a random string. * @param size Size of the random string. * @param defaultSize Size of the random string. * @param random A random bytes generator. * @typeparam Type The ID type to replace `string` with some opaque type. * @returns A random string generator. */export function customRandom<Type extends string>( alphabet: string, size: number, defaultSize: number, random: (bytes: number) => Uint8Array): (size?: number) => Type
/**22 unmodified linesmodified:index.js+106 added-41 removed
1 import { webcrypto as crypto } from 'node:crypto'2 3-import { urlAlphabet as scopedUrlAlphabet } from './url-alphabet/index.js'3+import { urlAlphabet } from './url-alphabet/index.js'4 5-export { urlAlphabet } from './url-alphabet/index.js'5+export { urlAlphabet }6 7-// 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.12-const POOL_SIZE_MULTIPLIER = 12813-let pool, poolOffset7+// `crypto.getRandomValues` rejects requests over 65536 bytes,8+// so bigger buffers are filled by chunks.9+const GET_RANDOM_LIMIT = 6553610 15-function 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 e11+function 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 }19 20 export 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 }30 31 export function customRandom(alphabet, defaultSize, getRandom) {32 // Random bytes are 0-255. `random % alphabet.length` can waste54 unmodified lines87 }88 }89 }90 100-export 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-id94 104-export 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()`.96+const POOL_MAX = GET_RANDOM_LIMIT / 297 109- 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]98+export 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+ }113+114+ // 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))) - 1122+123+ // 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 = 0134+135+ 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 }178+179+// `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.182+export const nanoid = customAlphabet(urlAlphabet)modified:README.ar.md+16 added-16 removed
12 unmodified lines13 > والتي يستحيل ألّا تحظى بالاحترام."14 15 - **صغير الحجم.** 118 بايت فقط (بعد التصغير والضغط ببروتلي). بدون أيّ اعتماديات خارجية.16 يتم التحكّم بالحجم عبر [Size Limit].17+- **سريع.** أسرع بنسبة 50% من `crypto.randomUUID()` الأصلية.18 - **آمن.** يستخدم مُولِّد أرقام عشوائية على مستوى العتاد. يمكن استخدامه في بيئات الكلستر.19 - **مُعرِّفات قصيرة.** يستخدم أبجدية أكبر من UUID وهي (`A-Za-z0-9_-`).20 لذا تم تقليص حجم المُعرِّف من 36 إلى 21 رمزًا.21 - **قابل للنقل.** تم نقل Nano ID55 unmodified lines77 يوجد اختلافان رئيسيان بين Nano ID و UUID v4:78 79 1. يستخدم Nano ID أبجدية أكبر، لذا يتم ضغط عدد مماثل من البتّات العشوائية80 في 21 رمزًا فقط بدلاً من 36.80-2. كود Nano ID أصغر بـ **4 مرات** من حزمة `uuid/v4`:81- 118 بايت مقابل 423.81+2. Nano ID أسرع من `crypto.randomUUID` و`uuid/v4`.82 83 ## اختبار الأداء84 85 </div>86 87 ```rust88 $ node ./test/benchmark.js89-nope-id 27,398,074 ops/sec90-crypto.randomUUID 14,055,107 ops/sec91-uuid v4 9,256,301 ops/sec92-@napi-rs/uuid 7,100,180 ops/sec93-uid/secure 7,312,765 ops/sec94-@lukeed/uuid 5,543,254 ops/sec95-nanoid 4,954,561 ops/sec96-customAlphabet 6,708,339 ops/sec97-nanoid for browser 497,980 ops/sec98-secure-random-string 412,049 ops/sec99-uid-safe.sync 420,669 ops/sec89+nope-id 20,386,830 ops/sec90+nanoid 20,434,827 ops/sec91+customAlphabet 20,544,476 ops/sec92+crypto.randomUUID 12,865,759 ops/sec93+uuid v4 7,930,104 ops/sec94+@napi-rs/uuid 5,573,171 ops/sec95+uid/secure 6,308,267 ops/sec96+@lukeed/uuid 5,278,597 ops/sec97+nanoid for browser 311,497 ops/sec98+secure-random-string 301,667 ops/sec99+uid-safe.sync 297,815 ops/sec100 101 Non-secure:102-uid 27,106,859 ops/sec103-nanoid/non-secure 2,672,540 ops/sec104-rndm 2,666,518 ops/sec102+uid 20,286,757 ops/sec103+nanoid/non-secure 2,397,594 ops/sec104+rndm 2,445,462 ops/sec105 ```106 107 <div dir="rtl">108 479 unmodified linesmodified:README.id-ID.md+16 added-15 removed
9 unmodified lines10 > "Sebuah tingkat kesempurnaan yang luar biasa,11 > yang mana tidak mungkin untuk tidak dihormati."12 13 - **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 lines58 59 Ada dua buah perbedaan antara Nano ID dan UUID v4:60 61 1. Nano ID menggunakan alfabet yang lebih lebar, karenanya jumlah bita acak dapat 'dikemas' dalam 21 simbol, bukan 36 simbol.61-2. Kode sumber Nano ID **empat kali lebih kecil** ketimbang `uuid/v4`: 118 bytes dibanding 423 bytes.62+2. Nano ID lebih cepat ketimbang `crypto.randomUUID` dan `uuid/v4`.63 64 ## Benchmark65 66 ```rust67 $ node ./test/benchmark.js67-nope-id 27,398,074 ops/sec68-crypto.randomUUID 14,055,107 ops/sec69-uuid v4 9,256,301 ops/sec70-@napi-rs/uuid 7,100,180 ops/sec71-uid/secure 7,312,765 ops/sec72-@lukeed/uuid 5,543,254 ops/sec73-nanoid 4,954,561 ops/sec74-customAlphabet 6,708,339 ops/sec75-nanoid for browser 497,980 ops/sec76-secure-random-string 412,049 ops/sec77-uid-safe.sync 420,669 ops/sec68+nope-id 20,386,830 ops/sec69+nanoid 20,434,827 ops/sec70+customAlphabet 20,544,476 ops/sec71+crypto.randomUUID 12,865,759 ops/sec72+uuid v4 7,930,104 ops/sec73+@napi-rs/uuid 5,573,171 ops/sec74+uid/secure 6,308,267 ops/sec75+@lukeed/uuid 5,278,597 ops/sec76+nanoid for browser 311,497 ops/sec77+secure-random-string 301,667 ops/sec78+uid-safe.sync 297,815 ops/sec79 80 Non-secure:80-uid 27,106,859 ops/sec81-nanoid/non-secure 2,672,540 ops/sec82-rndm 2,666,518 ops/sec81+uid 20,286,757 ops/sec82+nanoid/non-secure 2,397,594 ops/sec83+rndm 2,445,462 ops/sec84 ```85 86 Konfigurasi pengujian: Framework 13 7840U, Fedora 39, Node.js 21.6.87 258 unmodified linesmodified:README.ja.md+16 added-16 removed
10 unmodified lines11 > これは尊敬せざるを得ない。」12 13 - **小さい。** 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 lines70 Nano IDとUUID v4の主な違いは2つあります:71 72 1. Nano IDはより大きなアルファベットを使用するため、同様のランダムビット数が73 36文字ではなく21文字に詰め込まれています。73-2. Nano IDのコードはuuid/v4パッケージより**4倍小さい**です:74- 423バイトではなく118バイトです。74+2. Nano IDは`crypto.randomUUID`や`uuid/v4`よりも高速です。75 76 ## ベンチマーク77 78 ```rust79 $ node ./test/benchmark.js80-nope-id 27,398,074 ops/sec81-crypto.randomUUID 14,055,107 ops/sec82-uuid v4 9,256,301 ops/sec83-@napi-rs/uuid 7,100,180 ops/sec84-uid/secure 7,312,765 ops/sec85-@lukeed/uuid 5,543,254 ops/sec86-nanoid 4,954,561 ops/sec87-customAlphabet 6,708,339 ops/sec88-nanoid for browser 497,980 ops/sec89-secure-random-string 412,049 ops/sec90-uid-safe.sync 420,669 ops/sec80+nope-id 20,386,830 ops/sec81+nanoid 20,434,827 ops/sec82+customAlphabet 20,544,476 ops/sec83+crypto.randomUUID 12,865,759 ops/sec84+uuid v4 7,930,104 ops/sec85+@napi-rs/uuid 5,573,171 ops/sec86+uid/secure 6,308,267 ops/sec87+@lukeed/uuid 5,278,597 ops/sec88+nanoid for browser 311,497 ops/sec89+secure-random-string 301,667 ops/sec90+uid-safe.sync 297,815 ops/sec91 92 Non-secure:93-uid 27,106,859 ops/sec94-nanoid/non-secure 2,672,540 ops/sec95-rndm 2,666,518 ops/sec93+uid 20,286,757 ops/sec94+nanoid/non-secure 2,397,594 ops/sec95+rndm 2,445,462 ops/sec96 ```97 98 テスト構成:Framework 13 7840U, Fedora 39, Node.js 21.6.99 365 unmodified linesmodified:README.ko.md+16 added-16 removed
10 unmodified lines11 > 경의를 표하지 않을 수 없습니다”12 13 - **가볍습니다.** 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 lines69 70 Nano ID와 UUID v4에는 두 가지의 주요한 차이점이 있습니다:71 72 1. Nano ID는 대문자를 사용합니다. 그래서 유사한 개수의 랜덤 값을 36개가 아닌 21개의 문자로 나타낼 수 있습니다.72-2. Nano ID 코드는 `uuid/v4` 패키지보다 **4분의 1 사이즈**입니다:73- UUIDv4는 423 bytes, Nano ID는 118 bytes 입니다.73+2. Nano ID는 `crypto.randomUUID` 및 `uuid/v4` 보다 빠릅니다.74 75 ## 벤치마크76 77 ```rust78 $ node ./test/benchmark.js79-nope-id 27,398,074 ops/sec80-crypto.randomUUID 14,055,107 ops/sec81-uuid v4 9,256,301 ops/sec82-@napi-rs/uuid 7,100,180 ops/sec83-uid/secure 7,312,765 ops/sec84-@lukeed/uuid 5,543,254 ops/sec85-nanoid 4,954,561 ops/sec86-customAlphabet 6,708,339 ops/sec87-nanoid for browser 497,980 ops/sec88-secure-random-string 412,049 ops/sec89-uid-safe.sync 420,669 ops/sec79+nope-id 20,386,830 ops/sec80+nanoid 20,434,827 ops/sec81+customAlphabet 20,544,476 ops/sec82+crypto.randomUUID 12,865,759 ops/sec83+uuid v4 7,930,104 ops/sec84+@napi-rs/uuid 5,573,171 ops/sec85+uid/secure 6,308,267 ops/sec86+@lukeed/uuid 5,278,597 ops/sec87+nanoid for browser 311,497 ops/sec88+secure-random-string 301,667 ops/sec89+uid-safe.sync 297,815 ops/sec90 91 Non-secure:92-uid 27,106,859 ops/sec93-nanoid/non-secure 2,672,540 ops/sec94-rndm 2,666,518 ops/sec92+uid 20,286,757 ops/sec93+nanoid/non-secure 2,397,594 ops/sec94+rndm 2,445,462 ops/sec95 ```96 97 테스트 환경: 프레임워크 13 7840U, 페도라 39, Node.js 21.6.98 370 unmodified linesmodified:README.md+16 added-16 removed
10 unmodified lines11 > which is simply impossible not to respect.”12 13 - **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 ported51 unmodified lines71 There are two main differences between Nano ID and UUID v4:72 73 1. Nano ID uses a bigger alphabet, so a similar number of random bits74 are packed in just 21 symbols instead of 36.74-2. Nano ID code is **4 times smaller** than `uuid/v4` package:75- 118 bytes instead of 423.75+2. Nano ID is faster than `crypto.randomUUID` and `uuid/v4`.76 77 ## Benchmark78 79 ```rust80 $ node ./test/benchmark.js81-nope-id 27,398,074 ops/sec82-crypto.randomUUID 14,055,107 ops/sec83-uuid v4 9,256,301 ops/sec84-@napi-rs/uuid 7,100,180 ops/sec85-uid/secure 7,312,765 ops/sec86-@lukeed/uuid 5,543,254 ops/sec87-nanoid 4,954,561 ops/sec88-customAlphabet 6,708,339 ops/sec89-nanoid for browser 497,980 ops/sec90-secure-random-string 412,049 ops/sec91-uid-safe.sync 420,669 ops/sec81+nope-id 20,386,830 ops/sec82+nanoid 20,434,827 ops/sec83+customAlphabet 20,544,476 ops/sec84+crypto.randomUUID 12,865,759 ops/sec85+uuid v4 7,930,104 ops/sec86+@napi-rs/uuid 5,573,171 ops/sec87+uid/secure 6,308,267 ops/sec88+@lukeed/uuid 5,278,597 ops/sec89+nanoid for browser 311,497 ops/sec90+secure-random-string 301,667 ops/sec91+uid-safe.sync 297,815 ops/sec92 93 Non-secure:94-uid 27,106,859 ops/sec95-nanoid/non-secure 2,672,540 ops/sec96-rndm 2,666,518 ops/sec94+uid 20,286,757 ops/sec95+nanoid/non-secure 2,397,594 ops/sec96+rndm 2,445,462 ops/sec97 ```98 99 Test configuration: Framework 13 7840U, Fedora 39, Node.js 21.6.100 384 unmodified linesmodified:README.ru.md+16 added-15 removed
11 unmodified lines12 > который просто невозможно не уважать»13 14 - **Лёгкий.** 118 байт (после минификации и Brotli). Без зависимостей.15 [Size Limit] следит за размером.16+- **Быстрый.** На 50% быстрее нативного `crypto.randomUUID()`.17 - **Безопасный.** Использует аппаратный генератор случайных чисел.18 Можно использовать в кластерах машин.19 - **Короткие ID.** Используется больший алфавит, чем у UUID (`A-Za-z0-9_-`).20 Поэтому длина ID уменьшена с 36 до 21 символа.56 unmodified lines77 78 1. Nano ID использует более широкий алфавит, и сравнимое количество79 битов случайности будут упакованы в более короткую строку80 (21 символ, против 36 у UUID).80-2. Код Nano ID **в 4 раз меньше**, чем у `uuid/v4` — 118 байт против 423.81+2. Nano ID быстрее, чем `crypto.randomUUID` и `uuid/v4`.82 83 ## Сравнение производительности84 85 ```rust86 $ node ./test/benchmark.js86-nope-id 27,398,074 ops/sec87-crypto.randomUUID 14,055,107 ops/sec88-uuid v4 9,256,301 ops/sec89-@napi-rs/uuid 7,100,180 ops/sec90-uid/secure 7,312,765 ops/sec91-@lukeed/uuid 5,543,254 ops/sec92-nanoid 4,954,561 ops/sec93-customAlphabet 6,708,339 ops/sec94-nanoid for browser 497,980 ops/sec95-secure-random-string 412,049 ops/sec96-uid-safe.sync 420,669 ops/sec87+nope-id 20,386,830 ops/sec88+nanoid 20,434,827 ops/sec89+customAlphabet 20,544,476 ops/sec90+crypto.randomUUID 12,865,759 ops/sec91+uuid v4 7,930,104 ops/sec92+@napi-rs/uuid 5,573,171 ops/sec93+uid/secure 6,308,267 ops/sec94+@lukeed/uuid 5,278,597 ops/sec95+nanoid for browser 311,497 ops/sec96+secure-random-string 301,667 ops/sec97+uid-safe.sync 297,815 ops/sec98 99 Non-secure:99-uid 27,106,859 ops/sec100-nanoid/non-secure 2,672,540 ops/sec101-rndm 2,666,518 ops/sec100+uid 20,286,757 ops/sec101+nanoid/non-secure 2,397,594 ops/sec102+rndm 2,445,462 ops/sec103 ```104 105 Среда сравнения: Framework 13 7840U, Fedora 39, Node.js 21.6.106 359 unmodified linesmodified:README.zh-CN.md+16 added-15 removed
8 unmodified lines9 10 > “一个惊人的无意义的完美主义水平,这简直让人无法不敬佩。”11 12 - **小巧.** 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 lines65 Nano ID 和 UUID v4之间有两个主要区别:66 67 1. Nano ID 使用更大的字母表,所以类似数量的随机位68 被包装在21个符号中,而不是36个。68-2. Nano ID 代码比 `uuid/v4` 包少 **4倍**: 118字节而不是423字节.69+2. Nano ID 比 `crypto.randomUUID` 和 `uuid/v4` 更快。70 71 ## 基准值72 73 ```rust74 $ node ./test/benchmark.js74-nope-id 27,398,074 ops/sec75-crypto.randomUUID 14,055,107 ops/sec76-uuid v4 9,256,301 ops/sec77-@napi-rs/uuid 7,100,180 ops/sec78-uid/secure 7,312,765 ops/sec79-@lukeed/uuid 5,543,254 ops/sec80-nanoid 4,954,561 ops/sec81-customAlphabet 6,708,339 ops/sec82-nanoid for browser 497,980 ops/sec83-secure-random-string 412,049 ops/sec84-uid-safe.sync 420,669 ops/sec75+nope-id 20,386,830 ops/sec76+nanoid 20,434,827 ops/sec77+customAlphabet 20,544,476 ops/sec78+crypto.randomUUID 12,865,759 ops/sec79+uuid v4 7,930,104 ops/sec80+@napi-rs/uuid 5,573,171 ops/sec81+uid/secure 6,308,267 ops/sec82+@lukeed/uuid 5,278,597 ops/sec83+nanoid for browser 311,497 ops/sec84+secure-random-string 301,667 ops/sec85+uid-safe.sync 297,815 ops/sec86 87 Non-secure:87-uid 27,106,859 ops/sec88-nanoid/non-secure 2,672,540 ops/sec89-rndm 2,666,518 ops/sec88+uid 20,286,757 ops/sec89+nanoid/non-secure 2,397,594 ops/sec90+rndm 2,445,462 ops/sec91 ```92 93 测试配置: Framework 13 7840U, Fedora 39, Node.js 21.6.94 321 unmodified lines