generator loop vs iterator

Benchmark created on


Setup

class List {
    constructor() {
        this.n = this.p = this;
    }
    [Symbol.iterator]() {
        let current = this;
        return {
            next: () => {
                current = current.n;
                return {
                    done: current === this,
                    value: current
                };
            }
        };
    }
}
class List2 {
    constructor() {
        this.n = this.p = this;
    }
    *[Symbol.iterator]() {
        for (let current = this.n; current != this; current = current.n) {
            yield current;
        }
    }
}
const append = (element, data) => {
    // link data (list node)
    data.n = element;
    data.p = element.p;
    // link list
    element.p = element.p.n = data;
};

const list1 = new List
const list2 = new List2

for (let i = 0; i < 1000; ++i) {
	append(list1, { value: i })
	append(list2, { value: i })
}

Test runner

Ready to run.

Testing in
TestOps/sec
Loop
let summ = 0;
for (const e of list1) {
	summ += e.value;
}
console.log(summ);
ready
Generator
let summ = 0;
for (const e of list2) {
	summ += e.value;
}
console.log(summ);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.