What are the benefits of `let` in Swift?

 ̄綄美尐妖づ 提交于 2020-06-13 13:53:10

问题


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, ...).


回答1:


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.




回答2:


The correct answer for now is "probably not".

Providing additional information to the compiler is always wise, however, the compiler is already rather smart. In many cases it can see that a variable is actually a constant even if you use var, so saying let won't be any new information and it won't provide a benefit.

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



来源:https://stackoverflow.com/questions/31651558/what-are-the-benefits-of-let-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!