Skip to content

Instantly share code, notes, and snippets.

@trevnorris
Last active August 29, 2015 14:16
Show Gist options
  • Save trevnorris/de6a7fd5e92ff3d8ec9e to your computer and use it in GitHub Desktop.
Save trevnorris/de6a7fd5e92ff3d8ec9e to your computer and use it in GitHub Desktop.
Comparing generators with stateful objects, for performance
'use strict';
const ITER = 1e7;
let t;
function* G() {
let i = 0;
for (; i < ITER; i++)
yield i;
}
function H() {
return new HObj();
}
function HObj() {
this._i = 0;
}
function HNext(value, done) {
this.value = value;
this.done = done;
}
HObj.prototype.next = function next() {
if (this._i === ITER - 1)
return new HNext(undefined, true);
else
return new HNext(this._i++, false);
};
t = performance.now();
let g = G();
while (!g.next().done);
print(performance.now() - t);
t = performance.now();
let h = H();
while (!h.next().done);
print(performance.now() - t);
// Results with d8 4.2.77 compiled for Linux x64.release
// Output:
// 392.2
// 67.6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment