Static var vs static let

Hi
There is an opinion that a static var takes up less memory than static let. Confirm or refute this statement please.

If it is not let vs. var. It is stored vs. computed.

Compare:

struct MyType {
    static let storedGlobal1: String = "foo"
    static var storedGlobal2: String = "foo"
    static var computedGlobal: String { return "foo" }
}

Both storedGlobal1 and storedGlobal2 are initialized on first use. After that, they remain initialized forever. The only difference is that the second one is mutable - but this has nothing to do with the fact that both are initialized after their first use.

On the other side, computedGlobal produces a new value each time it is called, which is destroyed after use.

func doStuff() {
    let x = MyType.storedGlobal1
    let y = MyType.storedGlobal2
    let z = MyType.computedGlobal
}

doStuff()
// Now:
// - storedGlobal1 is initialized
// - storedGlobal2 is initialized
// - computedGlobal has created a value which has been destroyed since

In a way, one could tell that computed properties take less memory that stored ones, because they don't hold this memory (don't remain initialized) for the whole duration of the program.

But this is not the only difference between stored and computed properties, and you should take those other differences in account when you choose one or the other. See Properties for more information.

2 Likes

Obviously the example here is a simplification; literal constants themselves take up space in the program, so if you write static var foo = 123, the compiler will reserve space for the variable and space for the constant used to initialise it (it may even generate a function to initialise the variable, though I assume for POD constants it will just place the variable into an initialised data section — I haven't checked, mind). Additionally, for computed properties, the compiler will generate a function call when you access them, which will take up extra space.

The optimiser will also figure into the final outcome here, particularly with static let and computed properties where it may choose to inline the value (or the computation) into your code; if you access these things more than once, and if the computation generates more code than a load from a variable, then that will make your code larger.

TLDR: It's potentially quite complicated, and if you really care about how much space you're using you will need to actually test what difference it makes in your specific program.

6 Likes