I often have expensive linq queries embedded in Debug.Assert()
.
Ex: Debug.Assert(!orderShipmentStatusLogs.GroupBy(c => new { c.Id, c.StartDateTime }).Any(c => c.Count() > 1));
In this case orderShipmentStatusLogs can be a huge list - so this code may be slow.
For performance i'm asking myself whether that's smart or not, i know the Debug.Assert()
method gets removed in release mode, but from reading the docs:
Any arguments passed to the method or attribute are still type-checked by the compiler. https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.conditionalattribute?view=net-6.0
I'm a bit doubtfull.
So am I safe here or am i accidently slowing my app down by adding in heavy assertions? Is the parameter to Debug.Assert()
optimized away?
The entire Debug.Assert
line is optimised away when you build in Release mode. So:
Console.WriteLine("Before");
Debug.Assert(false);
Console.WriteLine("After");
Becomes:
Console.WriteLine("Before");
Console.WriteLine("After");
You can see this using SharpLab. In Debug mode the Assert
is still there but in Release it is gone.