Can you track when CoW triggers an Array to be copied?

Is there a feature in Xcode or Instruments, or a programming call like assert, that would allow me to track if mutating an Array will cause copy-on-write to trigger?

While profiling some code recently, Instruments was showing a lot of copies taking place when I didn't expect them. Annoyingly, I had forgetten that a class in the call chain was setting a local property that was causing the Array to have a second reference to it. It was an easy fix, but I was curious if there was a way I could better track this.

final class LayoutEngine {
  
  private var nodes: Array<LayoutNode>
  
  init(_ nodes: Array<LayoutNode>) { 
    self.nodes = nodes
  }

  func prepareToLayout() {
    // Perform a lot of work on `nodes `, ideally making sure
    // that a copy is not being triggered when it is mutated.
    // 
    // Something like this, though obviously this doesn't work:        
    assert(isKnownUniquelyReferenced(&nodes))
  }
}

The LayoutNodes might have been passed down through a call chain whereby if any intermediary had kept a local copy of them then they would inadvertently be triggering copy-on-write further down the line.

Just curious if there's something like an assert or other debugging technique I can use to track this.

macOS 12+, Xcode 13+

2 Likes