Possible Duplicate:
Performance Cost Of 'try'
I stumbled upon this remark in “Best Practices for Handling Exceptions” at MSDN:
” using exception handling is better because less code is executed in the normal case”
in the context of whether one should check for the state of an object before calling a method or just call the method and catch the exception. The above recommendation is when the event of an exception is rare.
Assuming the property check will not imply a costly calculation, but merely return a state value, how cheap is the execution cost of a try / catch block in the non-throwing case compared to a property check?
I am wondering about the recommendation, because even if the try / catch is free or near free, the called method will in many cases do a bunch of checks by it’s own.
Exceptions in .NET are very cheap unless they are raised. As soon as you raise an exception, the effective cost goes up quite a bit.
That being said, I’d strongly recommend programming to the most maintainable solution here, and worrying about the performance later if, and only if, it’s proving to be a problem after measurement.
A property get method which just returns state is optimized to be a field lookup, and is pretty much a single operation – anything will typically be slower than that later. However, I doubt that exception handling will cause any noticeable effect in your overall speed unless it’s in a very, very tight loop – in which case, the overall performance will likely not be worse than the checks you’d introduce to avoid the exception handling.