[英]Why does not compiler auto detect readonly structs?
C# 7.2 introduced the concept of readonly structs . C#7.2引入了只读结构的概念。 So basically we can now use the keyword
readonly struct
on any immutable struct whatsoever. 所以基本上我们现在可以在任何不可变结构上使用关键字
readonly struct
。 This reduces performance overhead as these structs can now be passed by reference with the new in
keyword and ref return
. 这降低了性能开销,因为这些结构现在可以通过引用传递新的
in
关键字和ref return
。
Why does not C# compiler make all of the immutable structs readonly
automatically and then use those ref
language features without asking? 为什么不C#编译器让所有的不可变结构的
readonly
自动,然后使用这些ref
的语言特性,而不问? I mean they are immutable anyway, what could go wrong if you passed them by reference everywhere? 我的意思是他们无论如何都是一成不变的,如果你通过引用到处传递它们会出现什么问题呢?
It is only meant as a possible perf optimization for large structures. 它仅仅意味着对大型结构可能的性能优化。 The kind you may end up with when replacing a class with a struct.
用结构替换类时最终可能会遇到的那种。 Small structs perform best when they are passed by value, the struct members can then be passed through CPU registers with no worry of having to propagate the changes back to the caller.
小结构在按值传递时表现最佳,然后结构成员可以通过CPU寄存器,而不必担心必须将更改传播回调用方。 Passing by reference requires an extra indirection on each member access, that nullifies one advantage of a struct.
通过引用传递需要在每个成员访问上额外间接,这使结构的一个优点无效。
Passing a large struct by value incurs the cost of copying the struct value at method entry and exit. 按值传递大型结构会导致在方法入口和出口处复制struct值的成本。 The jitter always assumes that member access needs to be fast, even if infrequent member access would make passing by reference more optimal.
抖动始终假定成员访问需要快速,即使不频繁的成员访问会使参考传递更加优化。 Technically the optimizer could figure out what would be the best choice, but that kind of flow analysis is quite hard to do correctly, optimizers always skirt the Halting Problem.
从技术上讲,优化器可以找出最佳选择,但是这种流分析很难正确完成,优化器总是能够避开停机问题。 And these language changes had to be made without requiring a change in the CLR and the jitter.
并且必须在不需要改变CLR和抖动的情况下进行这些语言更改。
So blindly applying in
(or ref) is not a good idea, you have to trade the cost of the extra indirection against the copying. 所以,盲目运用
in
(或ref)是不是一个好主意,你的交易对复印的额外的间接成本。 Realistically, this is something you contemplate when a profiler showed you that a particular method call is a bottleneck. 实际上,当探查器向您显示特定方法调用是瓶颈时,您会考虑这一点。 As the C# team did, I think these changes were inspired by making Roslyn faster.
正如C#团队所做的那样,我认为这些变化的灵感来自于让Roslyn更快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.