Naveen's Weblog

Bridge to future

Why Avoid Exception

Posted by codingsense on March 16, 2010


Hi,

Last week I was optimizing a module, as I was working I found that if exceptions are avoided then we can save lot of fruitful time. So made the below sample to see how much time we can save by avoiding an exception.

In below sample a method just iterates and another method throws an exception.




using System;

namespace ConsoleApplication1
{
class Program    
{
static void Main(string[] args)
{
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();

sw.Start();
loopProper();
sw.Stop();
Console.WriteLine("Looping Time : " + sw.ElapsedMilliseconds);

sw.Reset();
sw.Start();
ThrowException();
sw.Stop();
Console.WriteLine("Exception not hanlded Time : " + sw.ElapsedMilliseconds);

Console.Read();
}

static void loopProper()
{
for (long Index = 0; Index < 350000; Index++)
{

}
}

static void ThrowException()
{
long Temp = 0;
long Zero = 0;

try            
{
Temp = Temp / Zero;
}
catch (ArithmeticException ex)
{

}
}
}
}



After running the above sample we can find that an time taken by just one exception is approx around time taken by 3,50,000 iterations. So if we can avoid exceptions then we can do more fruitful work in the same time.

I dont mean that exception handling should not be used, but try to avoid it to maximum. If you can use some if conditions where you know the line might give an exception, and see how the performance increases.

Any about my output, the module had a algorithm that would take 80-85 sec to complete and after optimization its taking 2 sec to complete. Changes in logic of the algorithm and exception handling increased the performance drastically.

Happy learning,
Codingsense 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: