Possible Duplicate:
How slow are .NET exceptions?
Is there an overhead for throwing an exception and catching it right away? Is there a difference between this
void DoSomething(object basic)
{
try
{
if (basic == null)
throw new NullReferenceException("Any message");
else
{
//...
}
}
catch (Exception error)
{
_logger.WriteLog(error);
}
}
and this (here we don't throw exception):
void DoSomething(object basic)
{
try
{
if (basic == null)
{
_logger.WriteLog(new NullReferenceException("Any message");
return;
}
else
{
...
}
}
catch (Exception error)
{
_logger.WriteLog(error);
}
}
Will the second fragment be faster, or not?
Also I want to know why one solution is faster than another.
Exceptions are slower than all other program flow but not to the extent they should be avoided for performance reasons. However, they are not meant to be used for program flow. In your situation, you have a very valid alternative that is better than using exceptions. When you can predict a situation and handle it appropriately without exceptions, always do that. Also, don't use exceptions in normal program flow as a convenience.
Use exceptions when you have an unanticipated exceptional situation you can't handle directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With