Skip to content

Instantly share code, notes, and snippets.

@xevrem
Last active August 18, 2021 22:43
Show Gist options
  • Select an option

  • Save xevrem/29733c219019523be9baca12390d2aca to your computer and use it in GitHub Desktop.

Select an option

Save xevrem/29733c219019523be9baca12390d2aca to your computer and use it in GitHub Desktop.
array joining
const num = 100000;
const runs = 100;
function populate<T extends number>(arr: T[], prob: T): T[] {
for (let i = num; i--; ) {
if (Math.random() > prob) {
arr[i] = i as T;
}
}
return arr;
}
const foo = populate([], 0.5);
const bar = populate([], 0.5);
const baz = populate([], 0.5);
const entities = populate([], 0.25);
function* join<T>(ent: T[], ...components: T[][]): IterableIterator<T[]> {
for (let i = ent.length; i--; ) {
if (!ent[i]) continue;
let valid = true;
const result: T[] = [];
for (let j = components.length; j--; ) {
const value = components[j][i];
valid = value && valid;
if (!valid) break;
result.push(value);
}
if (valid) yield result;
}
return;
}
let startTime = 0,
stopTime = 0,
cumulativeTime = 0,
totalTime = 0;
for (let i = runs; i--; ) {
let count = 0;
startTime = performance.now();
for (const [f, br, bz] of join(entities, foo, bar, baz)) {
count = f && br && bz ? count + 1 : 0;
}
stopTime = performance.now();
cumulativeTime += stopTime - startTime;
totalTime += count;
}
console.log("time:", cumulativeTime / runs, totalTime / runs);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment