You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么Generator比可迭代类的性能慢这么多?

基于池化优化的crypto.getRandomValues随机数生成器实现对比

下面是两个通过结果池化优化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()

内容的提问来源于stack exchange,提问作者Chris_F

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 05:04:54