Thursday, June 19, 2014

Throw Fewer Exceptions - Performance Tips for Asp.net

Performance is must for any successful project. I will try to give you some performance tips in “Performance Tips” category in my blog.

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

React-select is very slow on larger list - Found solution - using react-window

 I had more than 4000 items in searchable dropdownlist. I have used react-select but it was very slow. finally I found complete solution to ...