而不是
Array
,它天真地将您的每面旗帜存储为
double
Uint8Array
,或其他无符号整数格式,这将使内存使用量减少至少64倍。
您需要修改初始化、切换和检查标志的方式。
初始化:
const BitArray = Uint8Array; // or Uint16Array, Uint32Array
const BITS_PER_ELEMENT = BitArray.BYTES_PER_ELEMENT * 8;
const BIT_SHIFT = Math.log2(BITS_PER_ELEMENT);
const BIT_MASK = BITS_PER_ELEMENT - 1;
let primes = new BitArray(Math.ceil(limit / BITS_PER_ELEMENT));
切换:
primes[z >> BIT_SHIFT] ^= 1 << (z & BIT_MASK);
检查:
if (primes[i >> BIT_SHIFT] & (1 << (i & BIT_MASK)))
任何选择
uint8数组
,
Uint16Array
,和
Uint32Array