Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@pauldraper
Last active August 23, 2019 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pauldraper/e1f43ec37d0ce04aab82272b8d7cf0b2 to your computer and use it in GitHub Desktop.
Save pauldraper/e1f43ec37d0ce04aab82272b8d7cf0b2 to your computer and use it in GitHub Desktop.
Generator vs Array vs Inline iteration

In this test, inline is 10x faster than arrayt which is 1.4x faster than generator.

#!#!/bin/node --expose-gc
function time(fn) {
if (global.gc) {
global.gc();
}
const start = process.hrtime.bigint();
fn();
const end = process.hrtime.bigint();
return end - start;
}
function* generator(start, end, interval = 1) {
while (start < end) {
yield start;
start += interval;
}
}
function array(start, end, interval = 1) {
const a = new Array(Math.floor(end - start) / interval);
for (let i = 0; i < a.length; i++) {
a[i] = start;
start += interval;
}
return a;
}
function iterate(numbers) {
for (const n of numbers) {
if (1e9 < n) {
process.exit(1);
}
}
}
function iterateInline(start, end, interval = 1) {
for (; start < end; start += interval) {
if (1e9 < start) {
process.exit(1);
}
}
}
for (let i = 20; i < 25; i++) {
for (let n = 0; n < 2; n++) {
console.log(
`generator 2^${i}\t${time(() => iterate(generator(0, Math.pow(2, i)))) /
1000n /
1000n} ms`,
);
console.log(
`array 2^${i}\t${time(() => iterate(array(0, Math.pow(2, i)))) /
1000n /
1000n} ms`,
);
console.log(
`inline 2^${i}\t${time(() => iterateInline(0, Math.pow(2, i))) /
1000n /
1000n} ms`,
);
}
console.log();
}
generator 2^20 25 ms
array 2^20 21 ms
inline 2^20 2 ms
generator 2^20 25 ms
array 2^20 20 ms
inline 2^20 2 ms
generator 2^21 47 ms
array 2^21 39 ms
inline 2^21 3 ms
generator 2^21 47 ms
array 2^21 32 ms
inline 2^21 3 ms
generator 2^22 90 ms
array 2^22 67 ms
inline 2^22 6 ms
generator 2^22 90 ms
array 2^22 66 ms
inline 2^22 6 ms
generator 2^23 188 ms
array 2^23 135 ms
inline 2^23 12 ms
generator 2^23 184 ms
array 2^23 132 ms
inline 2^23 13 ms
generator 2^24 367 ms
array 2^24 262 ms
inline 2^24 24 ms
generator 2^24 369 ms
array 2^24 256 ms
inline 2^24 25 ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment