Is there a performance difference between computed properties vs functions in Swift?

155 Views Asked by At

Lets say you have a SwiftUI view that has lots of expensive computed vars that call each-other on the main thread "spaghetti style" with state variables as the source of truth, such as:

// This is extremely simplified for basic illustration. These are much more numerous and expensive operations in real app with a complex web of dependencies where calling one could result in another being called several times.

@State var a:Double
@State var b:Double
@State var c:Double

var aTimesB:Double {
    return a * b
}

var bTimesC:Double {
    return b * c
}

var computation1:Double {
    return doSuperExpensiveThingWith(aTimesB + bTimesC)
}

Is it true that the result of computed vars like this are not cached at runtime (and therefore will be re-run even if not necessary, (for example, if we were to change value c, aTimesB would still re-compute anyway)) but if I were to change them into functions that take arguments instead of making spaghetti calls... like this:

@State var a:Double
@State var b:Double
@State var c:Double

func aTimesB(a:Double, b:Double) -> Double {
    return a * b
}

func bTimesC(b:Double, c:Double) -> Double {
    return b * c
}

func computation1(item1:Double, item2:Double) -> Double {
    return doSuperExpensiveThisWith(item1 + item2)
}

... that they would be cached (in the event that the arguments sent to them were found to be the same as the previous call), thus increasing performance?

1

There are 1 best solutions below

0
On

A computed property is "syntactic sugar", which is to say it's a language feature that does the same thing as something else, but in a way that reads better. Quoting the Wiki article on the topic:

syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer. Syntactic sugar is usually a shorthand for a common operation that could also be expressed in an alternate, more verbose, form"

A computed property is a function (or more accurately, a closure. But a closure is an anonymous function.) A computed property is a way of calling a closure that takes no parameters and returns a value. It makes it look to the reader as if the thing is a variable/property, but it's really code that gets evaluated.

I'd have to look at the generated assembler to be certain, but I'm willing to bet that with optimization turned on, there would be no difference in the compiler output between the two.