Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does not compiler auto detect readonly structs?

Tags:

c#

.net

struct

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?

like image 914
bashis Avatar asked Dec 13 '17 05:12

bashis


1 Answers

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.

like image 78
Hans Passant Avatar answered Oct 02 '22 10:10

Hans Passant