For-loop vs generator vs iterator (v2)

Revision 2 of this benchmark created on


Setup

array = [];
for (let i = 0; i < 100000; i++) {
	array.push(i);
}
function *range(n) { for (let i = 0; i < n; i++) yield i; }
class Range {
	constructor(n) {
		this.i = 0;
		this.n = n;
	}
	[Symbol.iterator]() { return this; }
	next() {
		if (this.i < this.n) {
			return {value: this.i++, done: false};
		} else {
			return {value: undefined, done: true};
		}
	}
}
class Range2 {
	constructor(n) {
		this.n = n;
		this.value = -1;
		this.done = false;
	}
	[Symbol.iterator]() { return this; }
	next() {
		this.value++;
		if (this.value >= this.n) {
			this.done = true;
		}
		return this;
	}
}

Test runner

Ready to run.

Testing in
TestOps/sec
For loop
for (let i = 0; i < array.length; i++) {
	array[i]++;
}
ready
Generator
for (const i of range(array.length)) {
	array[i]++;
}
ready
Iterator
for (const i of new Range(array.length)) {
	array[i]++;
}
ready
Iterator2 (non-allocating)
for (const i of new Range2(array.length)) {
	array[i]++;
}
ready

Revisions

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