Calling derived `allCases` of CaseIterable enum

Does calling derived allCases of CaseIterable enum make a new array every time?

Should I cache it somewhere if the enum has many cases?

Until someone comes with a specific answer, the general answer for most performance-related questions is that you should not care until it proves to be a bottleneck. See Knuth:

Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97 % of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3 %.

1 Like

Cc: @CodaFi

My limited understanding of the current implementation is that it adds a computed property, which returns a new array expression for each access.

enum Foo: CaseIterable {
  case bar, baz

  // @derived
  typealias AllCases = [Foo]

  // @derived
  static var allCases: AllCases {
    get {
      return [.bar, .baz]
    }
  }
}

SR-7152 is an open issue to investigate using a different AllCases collection.

1 Like