-
Notifications
You must be signed in to change notification settings - Fork 551
Open
Description
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
Labels
No labels