Modify c# language to optimize boxing of boolean values #7586
Replies: 3 comments 5 replies
-
This doesn't feel like a C# language issue? It'd be up to the runtime to interpret boxing differently for I do wonder if the runtime couldn't manage two singleton instances of boxed |
Beta Was this translation helpful? Give feedback.
-
Maybe with some SG magic to detect something like this void M(object passABoolHere)
{ }
M(true);
M(false);
M(my_bool); and generate static class BoxedBool
{
public static readonly object True = true;
public static readonly object False = false;
}
[InterceptorLocation(…)]
void MBool(bool passABoolHere)
=> M(passABoolHere ? BoxedBool.True : BoxedBool.False); And maybe emit some warnings M(true); // Box001: Value type boxed, interceptor kicks in
M(false); // Box001: Value type boxed, interceptor kicks in
M(my_bool); // Box001: Value type boxed, interceptor kicks in |
Beta Was this translation helpful? Give feedback.
-
Does Unsafe.Unbox cause problems? using System.Runtime.CompilerServices;
object boxedTrue = true;
Unsafe.Unbox<bool>(boxedTrue) = false;
Console.WriteLine(boxedTrue); // false |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
This issue has been brought up many times in the past in the runtime and in Roslyn:
dotnet/roslyn#39314
dotnet/runtime#7079
The key issue that it keeps coming back to is that the current behavior of boxing small values (mostly bool) is extremely ineffective both for allocations/GC churn and for CPU/latency.
Years ago in Exchange/Substrate it was discovered that the action of boxing bools was contributing 2-5% of allocations in various processes, with some as high as 5% like Exchange Web Services. This led to higher GC churn and higher COGs overall. To counter this we now use a BoxedConstants class in our code wherever possible - and would suggest other services do similar.
In a micro benchmark the results are quite evident:
Micro benchmarks aren't everything but combining the dump investigation from a few years ago and this micro benchmark in .Net 7 makes it pretty clear that this is still an issue.
All of the other posts were closed because it would involve the runtime going out of spec:
So, would it be absolutely crazy to change the wording of the spec here in some way to allow the runtime or compiler to consider ways to optimize this situation? I'm sure it would break one person's unit test somewhere, but it seems pretty reasonable to me considering some other breaking changes that have been allowed.
Beta Was this translation helpful? Give feedback.
All reactions