Why doesn't the compiler automatically detect readonly structs?

C # 7.2 introduces the concept of readonly structs . So basically, we can now use the readonly struct keyword for any immutable structure. This reduces the load on performance, because these structures can now be passed by reference with the new keyword in and ref return .

Why doesn't the C # compiler do all immutable readonly structures automatically, and then use those ref functions without asking? I mean, they are immutable anyway, what could go wrong if you passed them by reference everywhere?

+5
source share
1 answer

This means only possible initial optimization for large structures. The view that can occur when replacing a class with a structure. Small structures work best when they are passed by value, then members of the structure can be transmitted through the CPU registers without fear that they will transfer changes back to the caller. For passing by reference, an additional indirect appeal to each member access is required, which negates one advantage of the structure.

Passing a large structure by value carries the cost of copying the value of the struct when the method enters and exits. Jitter always assumes that access to a member should be fast, even if the odd access to a member will make link navigation more optimal. Technically, the optimizer can figure out what the best choice will be, but such a flow analysis is quite difficult to do correctly, optimizers always omit the problem with stopping. And these language changes had to be made without changing the CLR and jitter.

So blind application of in (or ref) is not a good idea, you should trade the cost of an extra copy pointer. Actually, this is what you are considering when the profiler shows you that a particular method call is a bottleneck. Like the C # team, I think these changes were inspired by the fact that Roslyn is faster.

+7
source

Source: https://habr.com/ru/post/1274018/


All Articles