为什么生成器比可迭代类慢得多?

Chr*_*s_F 9 javascript generator

我这里有两个 RNG 示例,它们通过池化结果来crypto.getRandomValues减少昂贵的系统调用的开销。基于类的方法基准测试为 378M ops/s,而生成器仅获得 56M ops/s。性能相差 6.75 倍。

class RandClass {
    #entropy; #index
    constructor(poolSize = 1024) {
        this.#entropy = new Uint32Array(poolSize)
        this.#index = 0
        crypto.getRandomValues(this.#entropy)
    }
    next() {
        const value = this.#entropy[this.#index++]
        if (this.#index === this.#entropy.length) {
            crypto.getRandomValues(this.#entropy)
            this.#index = 0
        }
        return { value, done: false }
    }
    [Symbol.iterator]() { return this }
}

const randClass = new RandClass()

function* RandGen(poolSize = 1024) {
    const entropy = new Uint32Array(poolSize)
    while (true) {
        crypto.getRandomValues(entropy)
        for (let i = 0; i < poolSize; ++i) {
            yield entropy[i]
        }
    }
}

const randGen = RandGen()
Run Code Online (Sandbox Code Playgroud)