Compiler optimization with computed properties

If the body of a computed property references another computed property multiple times, are there any guarantees—and if yes, under what conditions—that the latter will be optimized to a singular local value computation that is reused? A specific example that made me think about it:

struct T {}

class C {
  public var aRect: CGRect {
    CGRect(...)  // references a mix of stored and computed properties
  }
  public var t: T {
    // references multiple properties of aRect, e.g., aRect.minX, aRect.maxY,
    // aRect.size.width, etc. 
    return T(...)  // will presumably compute aRect multiple times
    // Compare with:
    // let r = self.aRect
    // return T(...)  // referencing the local `r`
  }
}

I know functions are cheap and what not, but would like to understand the behavior here and what can we do, if anything, to write the simplest yet most performant code possible.

2 Likes

It's no different than any other function call -- if the optimizer can see the body of the function and reason about it, it may be able to eliminate such redundancy, for example by inlining followed by common subexpression elimination. But in the language, there's no semantic guarantee that a call to a computed property getter is side effect-free, so in the general case we have no choice but to recompute the value on each access.

7 Likes