Swift Optimization Tips: Using Container Type Efficiently

Swift Optimization Tips: Using Container Type Efficiently

Hi! I'm following along with the Swift Optimization Tips documentation and had a few questions specifically about Using Container Types Efficiently.[1]

In the example from the documentation, we see a Swift.Array typed to a struct element:

// Don't use a class here.
struct PhonebookEntry {
  var name: String
  var number: [Int]
  ...
}

var a: [PhonebookEntry]

Alternatively, we could choose to define our element as a class:

class PhonebookEntry {
  var name: String
  var number: [Int]
  ...
}

var a: [PhonebookEntry]

However, the documentation recommends that choosing struct elements can lead to perf wins:

A key distinction [between value types and reference types] is that value types cannot be included inside an NSArray. Thus when using value types, the optimizer can remove most of the overhead in Array that is necessary to handle the possibility of the array being backed an NSArray.

We do qualify that advice by pointing out that complex struct types can introduce their own overhead when it comes to copying (and we discuss alternatives like optimizing with copy-on-write and "boxing")… but this is an orthogonal point to my main question.

The example from the documentation specifically calls out the perf wins we might see from choosing struct elements in Array… but can we assume there might be similar perf wins from choosing struct elements in Set (and struct values in Dictionary)? Does the support for bridging Set to NSSet (and Dictionary to NSDictionary) imply there exist similar compiler optimizations that take place when our Set or Dictionary is typed to struct elements?

The Swift documentation I found for Set[2] and Dictionary[3] don't seem to offer very many clues into this… does anyone know where that documentation would exist or where in the Swift repo I could see where those (potential) optimizations would be happening from? Thanks!


  1. swift/docs/OptimizationTips.rst at main · apple/swift · GitHub ↩︎

  2. Set | Apple Developer Documentation ↩︎

  3. Dictionary | Apple Developer Documentation ↩︎

1 Like

@lorentey Would you have any idea where else to look for any more public documentation or clues about that? Thanks!