Advantage of Computed Properties (Gettable Ones Only) VS. Stored Properties

Advantage of computed properties (gettable ones only) vs. stored properties

Computed Properties

var sayGoodMorningToUserComputed: String {
return greeting + username
}

sayGoodMorningToUserComputed acts just like a function. If a change has been made to greeting or username, then sayGoodMorningToUserComputed will return an up-to-date result that will be the concatenation of the current values.

You would want to use this if you want to ensure your returned value is computed off the latest values of its dependencies (greeting and username).

In the case that both dependencies are final, then it's very likely that the compiler would optimise this computed property into a stored property, because it knows the dependencies can't change

Stored properties

var sayGoodMorningToUserStored = greeting + username

sayGoodMorningToUserStored is just a variable, with nothing special going on. However, it's only set once, whenever the containing scope is initialized. It's computed once, stored and remains constant until it is overwritten by an external source. As such, if greeting or username changes, there will be no effect on sayGoodMorningToUserStored, because it's been computed from the old values, and stored.

You would want to use this if you want to improve performance by caching the result of a computation whose dependencies are constant.

What's the connection between gettable, settable and stored property, computed property

Computed properties:

  • Are not really properties at all
  • Do not have memory that stores their value
  • Are methods that present themselves as properties
  • Have a get and optional set method that can be overridden
  • Can be gettable, settable, or both.
  • Example usage:

    • Get a temperature in Celcius from a stored property that's stored in Kelvin
    • Get the area of a rectangle that's stored in a width and height stored property

Stored properties:

  • Are just like regular variables in other languages
  • Have memory that stores their value
  • Have a willSet(_:) and didSet(_:) method that can be overriden
  • Can always be read, but can be read only.
  • Example usage:

    • Store a temperature in Kelvin
    • Store a width and a height of a rectangle

Getter vs Computed property. What would warrant using one of these approaches over the other?

Both forms are exactly the same thing, a read-only computed property.

From the documentation:

You can simplify the declaration of a read-only computed property by
removing the get keyword and its braces.

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

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.

Difference between variables

The second variable var b is declared as a stored property:

In its simplest form, a stored property is a constant or variable that
is stored as part of an instance of a particular class or structure.
Stored properties can be either variable stored properties (introduced
by the var keyword) or constant stored properties (introduced by the
let keyword).

You could consider it as the default way for declaring properties.


The first variable var a is declared as a computed property:

In addition to stored properties, classes, structures, and
enumerations can define computed properties, which do not actually
store a value. Instead, they provide a getter and an optional setter
to retrieve and set other properties and values indirectly.

You should declare a computed property when you need to edit the value of a stored property or even getting a new type based on another stored property.

Example:

struct MyStruct {
// stored properties
var var1: Int
var var2: Int

// comupted properties
var multiplication: Int {
return var1 * var2
}

var result: String {
return "result is: \(multiplication)"
}
}

Keep in mind that computed properties do not store the value, instead it just acts like a regular function that returns a value of a type.

Also, you could treat the computed property as a getter-setter for your -private- stored properties, example:

struct AccessControlStruct {
private var stored: String

var computed: String {
get {
return stored
}

set {
stored = newValue.trimmingCharacters(in: .whitespaces)
}
}
}

Since stored declared as private, the only way is to access from out of the structure scope is by setting/getting its value by talking to computed. Obviously, you could any desired edit to the value before setting/getting it to/from stored, as an example, I am letting the newValue string of the computed to be trimmed before setting it to stored, it is also possible to edit the value before getting it.


Reference:

For more information, I would suggest to review:

The Swift Programming Language - Properties.

Advantages/Disadvantages of parsing data using initializer vs computed properties

I don't see any real advantage to the computed properties. I prefer the first option, because:

  1. This decouples your data model from the JSON. With the first option you can instantiate a DataModelOne without any JSON, and assign properties manually.
  2. It's clearer because the parsing happens in one place.
  3. You don't have to keep the dictionary around like you do with the computed properties. So if the dictionary contains a lot of other data that can be discarded, it can free up some memory.

The only advantage of the computed properties I can think of is that it delays accessing the Dictionary to the last moment. If you never access a property, it will never have to reach into the Dictionary in the first place. But the increase in performance will be negligible.

Lastly, I would rename the initialiser to something like init(values:). You're not initialising it with JSON, but with a plain Swift Dictionary.

C# class members access

If you are asking what's the point of having public get/set accessors when you could just make the actual field public, it's because then you have the freedom to change the class' private implementation of that field later, without changing client code. For example, you could add a check if the setter is getting valid input, or even change the datatype of the private field entirely, but translate it correctly in the setter.

edit:

SetName() as mentioned in commentaries, is an odd addition. It should actually change the name (and take a parameter), not return a string.

C# - Difference between Automatic Property and returning a backing field?

The primary difference between your Code1 and Code2 is that in #1, the property is settable.

You can achieve the same thing using automatic properties, because the setter can be private:

public int Temp { get; private set; }

Automatic properties was added in C#3, and is really just syntactic sugar for the longer version using a field. If you don't need to access the field directly, there is no reason not to use automatic properties. Automatic properties are equivalent to using a field - the compiler generates the field for you, it is just not accessible in code.



Related Topics



Leave a reply



Submit