Skip to content

Instantly share code, notes, and snippets.

@sccolbert
Last active April 26, 2018 14:44
Show Gist options
  • Save sccolbert/d52ee43edd79ada904fb5b5a3958ca49 to your computer and use it in GitHub Desktop.
Save sccolbert/d52ee43edd79ada904fb5b5a3958ca49 to your computer and use it in GitHub Desktop.
ES6 Iterator Timing
function foo() {
'use strict';
class MyArrayIterator {
constructor(source) {
this._index = 0;
this._source = source;
}
next() {
if (this._index >= this._source.length) {
return undefined;
}
return this._source[this._index++];
}
}
class ESArrayIterator {
constructor(source) {
this._index = 0;
this._source = source;
}
[Symbol.iterator]() {
return this;
}
next() {
if (this._index >= this._source.length) {
return { done: true };
}
return { done: false, value: this._source[this._index++] };
}
}
function mySum(it) {
let v;
let r = 0;
while ((v = it.next()) !== undefined) {
r += v;
}
return r;
}
function esSum(it) {
let r = 0;
for (let v of it) {
r += v;
}
return r;
}
function esSum2(it) {
let r = 0;
while (true) {
let { done, value } = it.next();
if (done) {
return r;
}
r += value;
}
}
function makeData() {
let data = [];
for (let i = 0; i < 1000000; ++i) {
data.push(Math.random());
}
return data;
}
var data = makeData();
function myTiming() {
let it = new MyArrayIterator(data);
let t1 = performance.now();
let r = mySum(it);
let t2 = performance.now();
return [r, t2 - t1];
}
function esTiming() {
let it = new ESArrayIterator(data);
let t1 = performance.now();
let r = esSum(it);
let t2 = performance.now();
return [r, t2 - t1];
}
function esTiming2() {
let it = new ESArrayIterator(data);
let t1 = performance.now();
let r = esSum2(it);
let t2 = performance.now();
return [r, t2 - t1];
}
return {myTiming, esTiming, esTiming2};
}
let things = foo();
myTiming = things.myTiming;
esTiming = things.esTiming;
esTiming2 = things.esTiming2;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment