c# - 条件方法 (Debug.Assert(...)) 的参数是否在 Release模式下被优化掉了?

标签 c# compilation precompile

我经常在 Debug.Assert() 中嵌入昂贵的 linq 查询。

例如:Debug.Assert(!orderShipmentStatusLogs.GroupBy(c => new { c.Id, c.StartDateTime }).Any(c => c.Count() > 1));

在这种情况下,orderShipmentStatusLogs 可能是一个巨大的列表 - 因此这段代码可能会很慢。

为了性能,我问自己这是否聪明,我知道 Debug.Assert() 方法在 Release模式下被删除,但是通过阅读文档:

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

我有点怀疑

那么我在这里安全吗,还是我通过添加大量断言不小心减慢了我的应用程序? Debug.Assert() 的参数是否优化掉了?

最佳答案

当您在 Release模式下构建时,整个 Debug.Assert 行都被优化掉了。所以:

Console.WriteLine("Before");
Debug.Assert(false);
Console.WriteLine("After");

变成:

Console.WriteLine("Before");
Console.WriteLine("After");

您可以使用 SharpLab 看到这一点。在 Debug Assert 模式仍然存在,但在 Release 中它不见了。

关于c# - 条件方法 (Debug.Assert(...)) 的参数是否在 Release模式下被优化掉了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70753625/

相关文章:

c# - 一个中间件应该总是调用下一个?

c# - 我可以通过编译器选项传递 VisualStudio 版本名称吗?

c# - 检查长度和非字母数字字符的 .NET 正则表达式

c# - WPF C# - 如何避免对任务栏图标进行分组?

compilation - 在 Jekyll 模板中设置全局变量

ruby-on-rails - 部署后 Rails 不使用新的 manifest-*.json 文件

android - 内部错误 : Could not find . pro 文件

.net - Windows 上的qyoto

ruby-on-rails - 如何在 Rails 3+ 中加速 Assets 预编译?

Java - 使用Ant自动生成样板代码