Tip 1. Throw Fewer Exceptions.
Throwing exceptions can be very expensive to your project. So make sure that you don’t throw a lot of them. I recommend that test your project thoroughly and try to handle all the error instead of throwing them and catching them into database. Why? See below example and its result. Note that this has nothing to do with try/catch blocks: you only incur the cost when the actual exception is thrown. You can use as many try/catch blocks as you want.
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); int j = 0; for (int i = 0; i < 1000; i++) { try { j = i / j; //Attempted to divide by zero. //This code will throw exception } catch { } } sw.Stop(); Response.Write("With exception : " + sw.ElapsedMilliseconds.ToString() + " Milliseconds."); sw = new System.Diagnostics.Stopwatch(); sw.Start(); j = 0; for (int i = 0; i < 1000; i++) { try { if (j > 0) //Handle like this will improve performance. { j = i / j; } } catch { } } sw.Stop(); Response.Write("WITHOUT exception : " + sw.ElapsedMilliseconds.ToString() + " Milliseconds.");
Result will be: With exception : 15772 Milliseconds. WITHOUT exception : 0 Milliseconds.
In above code, you can see clearly that if we handle error or try to eliminate it, it will improve performance tremendously.
No comments:
Post a Comment