shim
shim

Reputation: 10126

Swift - constant properties (e.g. strings) computed var vs let, any advantage?

It is quite common to have constants, such as strings, associated with a class, say a view controller.

Is there any computational benefit to writing these constants as computed vars as opposed to constant lets? (Yes in practice this is over-engineering, but I am still curious.)

For example:

let myConstant = "myConstant"

Versus:

var myConstant: String {
    "myConstant"
}

My thinking is that the former is stored in memory as long as the class it is a property of exists, whereas the latter is computed every time and thus does not take up as much additional memory.

Now, if the constant is something that isn't accessed very often (for example, setting text of a label just once when the view loads), it seems to me there may be some advantage to doing it this way, but I'm not sure if actually there is no difference whatsoever or the difference is negligible.

I guess this might fall under the category of a premature optimization, but if one or the other is better practice, might as well use it since it's quite simple and would be used everywhere in a project.

The only downside I can see is the extra lines of code and additional characters.

Upvotes: 2

Views: 509

Answers (1)

henrique
henrique

Reputation: 1112

IMHO, the memory used by the computed property will be always greater than the memory used by a let constant.

The reason is simple, you'll have the string myConstant probably in your symbol table, so the constant could be translated in just a pointer to the address of this string, while the computed var probably will be allocated on the stack as a function and then it'd return the pointer to the string in the symbol table.

Probably this makes a (really) small difference, and I'd assume that the compiler optimizes it when you have lots of accesses of the same address, somewhat like the compiler does with collections.

I do not have any docs to verify it but I think is reasonable ir order to visualize and understand a little about what's going on when using a constant constant or a computed property var.

Upvotes: 1

Related Questions