简体   繁体   中英

Why does not compiler auto detect readonly structs?

C# 7.2 introduced the concept of readonly structs . So basically we can now use the keyword readonly struct on any immutable struct whatsoever. This reduces performance overhead as these structs can now be passed by reference with the new in keyword and ref return .

Why does not C# compiler make all of the immutable structs readonly automatically and then use those ref language features without asking? 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. 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. 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.

So blindly applying in (or ref) is not a good idea, you have to trade the cost of the extra indirection against the copying. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM