开发者

.NET Exceptions: optimizing the exceptional case

Suppose I have a library that uses exceptions to indicate success or failure.

I expect the exceptions to be thrown a lot of times when I try requesting different properties of this library.

Now in .NET, it is said that开发者_JAVA技巧 trying costs nothing, but catching does. (Exception handling cost is in the exceptional case).

Is there a way to tell .NET to put the cost in installing the handler? Like in C++?

Clarifying: the calling code 'iterates' over all possible function argument values:

foreach( var enumvalue in Enum.GetValues( MyEnum ) ) {
   try {
      libraryObject.libFunction( enumvalue ); // will probably throw...
   } catch(ArgumentException) {
   }
}

Note: I know this is not a great API. It should be extended in order to iterate over the 'possible' values, or to work with return codes. I don't need answers that restate that.


I don't think there is a way to make exceptions cheap in .net. They build on structured exception handling and that is expensive. So short of rewriting the .net runtime I can't think of anything to make exception handling cheap. Possibly it's a bit faster on 64 bit systems since SEH works differently there.

The correct solution is to refactor the APIs that throw the exceptions to not throw so often. For example by returning status codes. If they are third party code you can't change, then I have no idea how to improve your performance.

Or you could write code similar to the one that throws the exception that detects the error conditions beforehand. So you don't call the API anymore if you know it will throw. While this violates DRY, with third party code this might still be the only viable solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜