我经常在 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/