【发布时间】:2014-09-29 00:11:06
【问题描述】:
我有一个每秒被调用超过 100 次的方法,由于它的内部实现,它经常抛出异常。
由于方法的内部实现,无法阻止这些异常,但我想降低这些异常的性能成本,例如通过禁用异常的堆栈跟踪收集,因为这些信息对我来说并不方便。
有什么想法吗?
方法实现:
public static TValue GetValue<TObj, TValue>(this TObj obj, Func<TObj, TValue> member, TValue defaultValueOnNull = default(TValue))
{
if (member == null)
throw new ArgumentNullException("member");
if (obj == null)
throw new ArgumentNullException("obj");
try
{
return member(obj); // We've lots of null reference exceptions here.
// And I'm not interested in stack trace of those exceptions, how to reduce performance costs here ?
}
catch (NullReferenceException)
{
return defaultValueOnNull;
}
}
方法用法:
String flightNumber = originDestinationInformation.GetValue(dest => dest.OriginDestinationOption.FlighInfo.FlightNumber, "");
【问题讨论】:
-
NullReferenceException是您必须防止不捕获的东西。 -
如果有一些神奇的标志来做到这一点,系统将仍然必须一直向上遍历各种堆栈帧,执行展开等,直到 找到那个神奇的旗帜。它不会在性能方面节省太多。
-
@SriramSakthivel 是的,你说得对,但我已经使用这种方法来获得更清晰的代码,而无需对对象进行大量“如果非空”检查。
-
@YasserMoradi 很抱歉这么说:您的评论很荒谬。如果您不想检查空使用NullObject Pattern,则不应捕获
NullReferenceException。恕我直言,捕获NullReferenceException的代码是废话。 -
那你为什么有
if (member == null)和if (obj == null)支票呢?您可以消除它并获得更好的代码,不是吗?
标签: c# .net performance exception-handling clr