Skip to content

Performance: O(n²) array concatenation in build methods #148

@grimmdude

Description

@grimmdude

Description

Several hot paths use array = array.concat(...) inside loops, which copies the entire array on every iteration, resulting in O(n²) time and memory usage.

Affected locations

  1. Track.buildData() (src/chunks/track.ts, lines 104, 109, 113, 121)

    this.data = this.data.concat(built.data);
  2. Writer.buildFile() (src/writer.ts, line 45)

    build = build.concat(d.type, d.size, d.data);
  3. Writer.base64() (src/writer.ts, lines 56-62) — string concatenation in a loop

    binary += String.fromCharCode(bytes[i]);

Impact

For a track with N events, each concat copies all previously accumulated data. This turns linear work into quadratic. Unlikely to matter for small files, but noticeable for larger multi-track compositions.

Suggested Fix

Replace concat with push(...spread) or collect chunks and flatten once:

// Instead of:
this.data = this.data.concat(built.data);

// Use:
this.data.push(...built.data);

For the string concatenation in base64(), collect into an array and join:

const chars = new Array(len);
for (let i = 0; i < len; i++) {
    chars[i] = String.fromCharCode(bytes[i]);
}
const binary = chars.join('');

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions