In performance-sensitive code, avoid doing expensive operations repeatedly inside loops (repeated flattening/sorting, repeated filesystem attribute resolution, repeated regex/compiler/formatter construction, repeated list+search scans). Also ensure your tree/hierarchy logic uses consistent keys for both ordering and relationship detection.
Apply these practices:
Example (hoist cached regex):
extension GraphBuilder {
private static let argSubRegex: NSRegularExpression = {
try! NSRegularExpression(pattern: #"\$\{([A-Za-z_][A-Za-z0-9_]*)\}"#)
}()
func substituteArgs(_ input: String, inFromContext: Bool) -> String {
// use Self.argSubRegex here (don’t compile per call)
// ...
return input
}
}
Example (avoid reserveCapacity mismatch):
let mounts = mounts.dedupe()
var result: [Filesystem] = []
result.reserveCapacity(mounts.count)
If a change introduces a new loop over many elements, re-check for inner-loop allocations, repeated sorting/flattening, repeated filesystem operations, and repeated scans/caches not being reused.