为什么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
相关产品推荐
相关产品推荐

