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