Home > Back-end >  Swift variable conditional initialization: var with default value or let?
Swift variable conditional initialization: var with default value or let?

Time:05-20

In case of a variable that never mutates after initialization, does having a var cause a performance hit? There are situations where it's simpler to write

var value = 0
if conditions {
    value = 1
}

than

let value: Int
if conditions {
    value = 1
} else {
    value = 0
}

Is it negligible?

CodePudding user response:

You can check it yourself, using a compiler explorer such as godbolt.

Compiled assembly from both methods is essentially identical, the jumps are just in different places, so there should be no performance difference whatsoever.

The scope of the variable is important though, when talking about local variables, the compiler should be able to optimise mutable local variables to the same compiled code as immutable ones (assuming your original example), but when talking about instance properties for instance, that is not necessarily the case anymore. The larger the scope of a variable, the harder it is to reason about whether it is ever mutated if you declared it mutable.

Modern compilers employ clever and efficient optimisations, so unless you work in a very restricted hardware environment (such as embedded systems with microcontrollers), which is usually not the case when developing with Swift, you shouldn't think about such micro optimisations (or rather premature optimisations).

  • Related