在Swift中`let`有什么好处? [英] What are the benefits of `let` in Swift?

查看:91
本文介绍了在Swift中`let`有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 Swift 确实鼓励我们的程序员使用常量( let )而不是变量( var

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

推荐答案

您问 ...是否有一些性能优化

You asked "...are there some performance optimisations the compiler does apply when we use constants instead of variables?"

答案是肯定的。

可变集合的组织方式可能与不可变集合的组织方式有所不同,以便可以对其进行更改。不可变集合可以针对只读操作进行优化。

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.

不可变对象的比较(

Sulthan关于编译器智能的观点是一个很好的观点。编译器通常可以从代码分析中推断出变量永远不会改变,这会使基准测试与var使用变得困难。

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.

这篇关于在Swift中`let`有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆