3

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?

Liam
  • 27,717
  • 28
  • 128
  • 190
sommmen
  • 6,570
  • 2
  • 30
  • 51

1 Answers1

1

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.

DavidG
  • 113,891
  • 12
  • 217
  • 223
  • Cool - good to know. Even variables only used in the assert get optimized away which is useful for inspecting the value in the assert: https://sharplab.io/#v2:CYLg1APgAgTAjAWAFBQAwAIpwHQBECWAhgOYB2A9gM4Au+AxpQNzLJYCcAFAEQBCApgDNyAJz5cAlMyQA3QsPQBbAJ4A1OegC86asICufKbj4AjXcWwBBSpT7DqHZWuGTWcTlwsDqtiVJZIgA=== – sommmen Jan 18 '22 at 10:27
  • The variable would be removed by normal optimisations anyway. Once the Assert line is removed, the variable is left as unused which the compiler can remove. The problem you might be left with if you use a variable, is that the right hand side might still get left in. Example https://sharplab.io/#v2:D4AQTAjAsAUCAMACEEB0ARAlgQwOYDsB7AZwBdMBjYgbllhQE4AKAIgCEBTAM0ICcOWASlowAbtl6IAtgE8AahMQBeRAHEOpAMqkArly5NhsdBwBGO3KgCCxYh16kmshbyNwIzFla6l7QkXQwpoSEADZqGtp6BoKwAN6wiEnIAOyIpLw6HCIAvkA – DavidG Jan 18 '22 at 10:32
  • That's also good to know! – sommmen Jan 18 '22 at 10:36