What are the benefits of `let` in Swift?

I know that Swift encourages us programmers to use constants ( let ) instead of variables ( var ) every time that makes sense.

This is good because we provide the compiler with more detailed information about what our code means, and the compiler can better prevent us from making mistakes (for example, changing some value that should not be changed).

My question is: is there a performance optimization that the compiler applies when we use constants instead of variables ? (e.g. faster execution time, less footprint, ...).

+8
performance constants swift
source share
2 answers

You asked: "... is there a performance optimization that the compiler applies when we use constants instead of variables?"

Answer: yes, absolutely.

Mutated collections can be organized differently than immutable collections so that they can be changed. Immutable collections can be optimized for read-only work.

Then the use of mutable / immutable objects is used. The compiler may need to generate code that copies the modified object when it is shared as a property of another object in order to avoid unwanted side effects.

Comparison of immutable objects (equivalent / comparable) can also be optimized so that mutable objects cannot.

The sultan compiler intelligence question is good. The compiler can often infer that the variable will never change from code analysis, which can lead to comparative testing, allowing the use of vs. var.

+10
source share

The correct answer at the moment is "maybe not."

Providing additional information to the compiler is always wise, but the compiler is already pretty smart. In many cases, he can see that the variable is actually a constant, even if you use var , so let there be no new information and it will not be useful.

The biggest advantage of const / let is its protection against programming errors. It may have some performance advantages in very specific cases, but modern compilers really don't need a programmer to tell them that a variable is assigned only once.

+7
source share

All Articles