Skip to content

perf(modeling): Inefficient recursive flatten utility uses O(n²) concat #1422

@jbroll

Description

@jbroll

Summary

The flatten() utility uses recursive concat() which creates a new array for every element processed.

Usage Frequency: EXTREMELY HIGH

Used by 48 files across the entire codebase:

  • All transform operations (translate, rotate, scale, mirror, align, center)
  • All boolean operations (union, subtract, intersect, scission)
  • All hull operations
  • All measurement functions
  • Color operations

Typical model usage: Called on virtually every operation that accepts multiple geometries. A model with 10 operations might call flatten 50+ times.

Problem

File: packages/modeling/src/utils/flatten.js
Line: 8

const flatten = (arr) => arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val), [])

This creates a new array for every single element via concat(). For an array of N elements (including nested), this performs N array allocations and O(n²) total copying.

Suggested Fix

Use modern Array.flat() or an iterative approach:

// Modern JS (Node 11+):
const flatten = (arr) => arr.flat(Infinity)

// Or iterative for older environments:
const flatten = (arr) => {
  const result = []
  const stack = [...arr]
  while (stack.length) {
    const item = stack.pop()
    if (Array.isArray(item)) {
      stack.push(...item)
    } else {
      result.push(item)
    }
  }
  return result.reverse()
}

Impact

HIGH - this is called constantly. Every union([a, b, c]) or translate([1,0,0], a, b) uses flatten.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions