Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Performance: Avoid spread, prefer batching pushTo #311

Merged
merged 3 commits into from
Oct 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion packages/core/src/InputDevice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,12 @@ export class InputDevice {
for(const link of links) {
const batch = this.memory.pullLinkItems(link.id, remaining)

pulled.push(...batch)
if(batch.length < 1000) {
pulled.push.apply(pulled, batch)
} else {
for(const item of batch) pulled.push(item)
}

remaining -= batch.length
if(remaining === 0) break
}
Expand Down
43 changes: 33 additions & 10 deletions packages/core/src/computers/Clone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ export const Clone: Computer = {
],
outputs: [
{
name: 'original',
name: 'clones',
schema: {}
},
{
name: 'clones',
name: 'original',
schema: {}
},
],
Expand All @@ -30,20 +30,43 @@ export const Clone: Computer = {
],

async *run({ input, output, params }) {
while(true) {
const incoming = input.pull()
output.pushTo('original', incoming)
while (true) {
const startTime = Date.now();

const incoming = input.pull();
output.pushTo('original', incoming);

const count = Number(params.count)
const count = Number(params.count);
const clones = [];
const BATCH_SIZE = 10000; // Adjust based on your memory constraints

for (let i = 0; i < count; i++) {
output.pushTo('clones', incoming.map(item => ({
...item.value,
_clone_id: i,
})))
for (const item of incoming) {
// Efficient object cloning without spread operator
const clonedItem = Object.assign({}, item.value, { _clone_id: i });
clones.push(clonedItem);

// Push in batches to manage memory
if (clones.length >= BATCH_SIZE) {
await output.pushTo('clones', clones.splice(0, BATCH_SIZE));
}
}
}

// Push any remaining clones
if (clones.length > 0) {
await output.pushTo('clones', clones);
}

// Clear large arrays to free memory
incoming.length = 0;
clones.length = 0;

const endTime = Date.now();
console.log('Clone time:', endTime - startTime, 'ms');

yield;
}
},

};