每个UUID版本——v1到v8——包含结构图、用例、碰撞风险和JavaScript代码示例。
结构
timestamp (60-bit) + clock seq (14-bit) + MAC (48-bit)
碰撞风险
Very low
优点
缺点
最佳用途
Legacy systems. Avoid in new projects due to MAC address exposure.
结构
MD5(namespace UUID + name) → UUID
碰撞风险
MD5 collision risk (low for UUIDs)
优点
缺点
最佳用途
Generating UUIDs from URLs, email addresses, or other stable identifiers. Use v5 instead.
结构
122 random bits + 4-bit version + 2-bit variant
碰撞风险
Negligible (2^122 possibilities)
优点
缺点
最佳用途
Default choice for most applications. IDs for records, sessions, tokens.
结构
SHA-1(namespace UUID + name) → UUID (top 128 bits)
碰撞风险
SHA-1 — extremely low for UUID purposes
优点
缺点
最佳用途
Deterministic IDs from a namespace + name. Example: UUID for 'https://example.com' is always the same.
结构
Unix ms timestamp (48-bit) + version (4-bit) + random (74-bit)
碰撞风险
Very low (74 random bits)
优点
缺点
最佳用途
Database primary keys where sort order matters. Replaces v1 for time-ordered UUIDs.
结构
128 bits, content defined by the implementation
碰撞风险
Depends on implementation
优点
缺点
最佳用途
Experimental or vendor-specific use cases where v1–v7 don't fit.
| Version | Method | Sortable | Privacy-safe | Deterministic |
|---|---|---|---|---|
| v1 | Time + MAC | ✅ | ❌ (MAC leak) | ❌ |
| v3 | MD5 hash | ❌ | ✅ | ✅ |
| v4 | Random | ❌ | ✅ | ❌ |
| v5 | SHA-1 hash | ❌ | ✅ | ✅ |
| v7 | Time + Random | ✅ | ✅ | ❌ |
| v8 | Custom | — | — | — |
// JavaScript / Node.js (built-in, Node 15+)
import { randomUUID } from 'crypto';
const v4 = randomUUID(); // → "550e8400-e29b-41d4-a716-446655440000"
// Browser
const v4 = crypto.randomUUID();
// UUID v7 (npm: uuid package v10+)
import { v7 as uuidv7 } from 'uuid';
const v7 = uuidv7(); // → "018f0b2d-4c9e-7abc-89de-f012345678ab"
// Python
import uuid
v4 = str(uuid.uuid4()) # Random
v5 = str(uuid.uuid5(uuid.NAMESPACE_URL, 'https://example.com'))
# PostgreSQL
SELECT gen_random_uuid(); -- v4 (pg 13+)
SELECT uuid_generate_v4(); -- v4 (uuid-ossp extension)
SELECT gen_random_uuid()::text; -- as textUUID(通用唯一标识符)是RFC 4122中标准化的128位标识符。格式为8-4-4-4-12十六进制字符,由连字符分隔。它们被设计为在没有中央机构的情况下在时间和空间上都是唯一的。
大多数一般用途使用v4——它是随机生成的,碰撞概率极低。如果您需要时间有序的UUID作为数据库主键,请使用v7。如果需要从命名空间+名称对生成确定性UUID,请使用v5。在新项目中避免使用v1,因为它会暴露MAC地址。
UUID v4是纯随机的(122个随机位)。UUID v7在前48位中编码Unix时间戳,后面跟随机位。这使v7 UUID可以按创建时间排序,显著提高了数据库中B-tree索引的性能。
实际上是的。UUID v4有122个随机位,给出2^122≈5.3×10^36个可能的值。要有50%的碰撞概率,您需要生成约2.7×10^18个UUID——远超任何实际应用。