uint32array 可高效实现位图索引,将百万布尔值压缩至几mb内存,支持o(1)读取与位运算筛选;每位对应一个布尔状态,通过 wordindex = i >> 5 和 bitindex = i & 31 定位并用位运算操作。

Uint32Array 是 JavaScript 中高效操作整数位的底层工具,非常适合实现位图索引——它能把百万级布尔状态压缩到几 MB 内存,并支持 O(1) 的随机读取和快速位运算(如 AND/OR)做多条件筛选。
位图索引的核心思想
不为每个布尔值单独分配 1 字节(甚至 1 位在 JS 中无法直接寻址),而是把连续的布尔状态映射到 Uint32Array 的每一位上:
- 每个 Uint32Array 元素是 32 位无符号整数,可存 32 个 true/false;
- 索引 i 对应的布尔值,落在第 Math.floor(i / 32) 个数组元素、第 i % 32 位上;
- 用位运算(&、|、、<code>>>>)读写单一位,避免布尔数组的内存与 GC 开销。
基础操作:设置、读取、翻转
假设要管理 100 万个布尔状态(即 1e6 个 bit):
```js
const size = 1_000_000;
const words = Math.ceil(size / 32); // 需要 31250 个 uint32
const bitmap = new Uint32Array(words);
// 设置第 i 位为 true
function set(bitmap, i) {
const wordIndex = (i / 32) | 0;
const bitIndex = i % 32;
bitmap[wordIndex] |= 1 }
// 读取第 i 位(返回 true/false)
function get(bitmap, i) {
const wordIndex = (i / 32) | 0;
const bitIndex = i % 32;
return !!(bitmap[wordIndex] & (1 }
// 清零第 i 位
function clear(bitmap, i) {
const wordIndex = (i / 32) | 0;
const bitIndex = i % 32;
bitmap[wordIndex] &= ~(1 }
```
多条件查询:位图布尔运算加速筛选
当有多个字段(如 is_active、is_premium、has_paid)时,为每类状态维护独立的 Uint32Array,查询“活跃且已付费用户”就变成两个位图的按位与:
- 预构建位图:// 每个用户 ID 对应相同索引位置
const isActive = new Uint32Array(words);
const hasPaid = new Uint32Array(words); - 执行联合查询:
```js
const result = new Uint32Array(words);
for (let i = 0; i result[i] = isActive[i] & hasPaid[i]; // 交集
}
``` - 快速统计或遍历结果:
用result[i]的非零值定位哪些 word 有匹配,再用countTrailingZeros或查表法(如 `BitLength` 表)快速枚举置位索引。
实战注意点
- Uint32Array 是小端序,但位索引与字节序无关,只关心位偏移(0–31),无需转换;
- JS 没有原生 popcount(统计 1 的个数),可用
BigInt.prototype.bitLength(需转 BigInt)或查表法(32 项静态数组); - 超过 2³² 位(约 5.12 亿条记录)需分段管理多个 Uint32Array,或改用 BigInt + 模拟位操作;
- 避免频繁创建新数组做布尔运算,尽量复用缓冲区或使用
TypedArray.set()原地更新。










