I know Swift does encourage us programmers to use constants (let
) instead of variables (var
) everytime it makes sense.
This is a good thing because we are providing more details to the compiler about what our code means and the compiler can better prevent us from making mistakes (e.g. changing some value that should not be changed).
My question is, are there some performance optimizations the compiler does apply when we use constants instead of variables? (e.g. faster executions times, lower footprint, ...).
In swift, we use the let keyword to declare a constant variable, a constant is a variable that once declared, the value can not be changed.
Let is an immutable variable, meaning that it cannot be changed, other languages call this a constant.
Swift lets you create both variables and constants as ways to reference your data, but there's a strong push (even Xcode warnings!) if you create things as variables then never change them. To make a constant, use let like this: let x = 10.
Since classes are reference objects the only difference between let and var is the ability to reassign the variable to a different class of the same type. The let and var keywords do not affect the ability to change a variable on a class.
You asked "...are there some performance optimisations the compiler does apply when we use constants instead of variables?"
The answer is yes, absolutely.
Mutable collections may be organized differently than immutable ones in order to allow for them to be changed. Immutable collections can be optimized for read-only operation.
Then there is the use of mutable/immutable objects. The compiler may have to generate code that copies a mutable object when it's shared as a property of another object in order to avoid undesired side-effects.
Comparison of immutable objects (equatable/comparable) can also be optimized in ways that mutable objects can't.
Sulthan's point about the intelligence of the compiler is a good one though. The compiler can often deduce that a variable is never going to change from code analysis, which can make benchmarking let vs. var usage hard.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With