问题描述
Const
被烘焙到客户端代码中.Readonly
不是.但是 const
更快.不过可能只有一点点.
Const
is baked into the client code. Readonly
isn't. But const
is faster. May be only slightly though.
问题是,在任何情况下您应该更喜欢 const
而不是 readonly
?或者换种说法,我们实际上总是最好使用 readonly
而不是 const
(记住上面所说的烘焙事情)?
The question is, is there ever any scenario where you should prefer const
over readonly
? Or to rephrase, are we not practically always better off using a readonly
instead of a const
(keeping in mind the above-said baking thing)?
推荐答案
我相信const"唯一合适的时候是当你编写的规范比你编写的程序更耐用时.例如,如果您正在实现 HTTP 协议,则为GET"设置一个 const 成员是合适的,因为它永远不会改变,并且客户端当然可以将其硬编码到他们编译的应用程序中,而不必担心您需要更改以后的价值.
I believe the only time "const" is appropriate is when there is a spec that you're coding against that is more durable than the program you're writing. For instance, if you're implementing the HTTP protocol, having a const member for "GET" is appropriate because that will never change, and clients can certainly hard-code that into their compiled apps without worrying that you'll need to change the value later.
如果您有任何机会在未来版本中更改该值,请不要使用 const.
If there's any chance at all you need to change the value in future versions, don't use const.
哦!除非你已经测量过,否则永远不要假设 const 比只读字段快.有 JIT 优化可以做到这一点,所以它实际上是完全一样的.
Oh! And never assume const is faster than a readonly field unless you've measured it. There are JIT optimizations that may make it so it's actually exactly the same.
这篇关于什么时候,如果有的话,我们应该使用 const 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!