for vs for...of

Benchmark created on


Setup

const _arrLen = 10000000
const arr = new Array(_arrLen);
for (let i = 0; i < _arrLen; i++) {
	arr[i] = {
		a: i,
		b: i / 2,
		r: 0,
	};
}

let total = 0;

Test runner

Ready to run.

Testing in
TestOps/sec
for
for (let i = 0; i < arr.length; i++) {
	const el = arr[i];
	total += el.a + el.b;
}
ready
for - cached len
const len = arr.length;
for (let i = 0; i < len; i++) {
	total += arr[i].a + arr[i].b;
}
ready
for - cached len, inner tmp var
const len = arr.length;
for (let i = 0; i < len; i++) {
	const tmp = arr[i];
	total += tmp.a + tmp.b;
}
ready
for - cached len, outer tmp var
const len = arr.length;
let tmp;
for (let i = 0; i < len; i++) {
	tmp = arr[i];
	total += tmp.a + tmp.b;
}
ready
for...of
let total = 0;

for (const el of arr) {
	total += el.a + el.b;
}
ready

Revisions

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