我想知道是否有人知道什么会更快以及为什么。
做: this.data[字节] |= 1 << bitIndex;
或者做1: const BIT_MASKS: Uint8Array = new Uint8Array([1, 2, 4, 8, 16, 32, 64, 128]);
this.data[字节] |= BIT_MASKS[位索引];
BIT_MASK
由于数组元素访问速度较慢,比按位操作昂贵得多,无需预缓存:
` Chrome/125
------------------------------------------------
shift ■ 1.00x | x1000000000 399 406 407 408 413
mask 1.12x | x1000000000 445 454 461 462 466
------------------------------------------------ `
let num = 100, bitIndex = 1;
// @benchmark shift
num |= 1 << bitIndex;
// @benchmark mask
const BIT_MASKS = new Uint8Array([1, 2, 4, 8, 16, 32, 64, 128]);
// @run
num |= BIT_MASKS[bitIndex];
/*@skip*/ fetch('https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js').then(r => r.text().then(eval));