markneustadt.com

Performance – Using Try/Catch

I just wrote the stupidest program ever.  It is inefficient by design.  If anyone did this thinking “hey… this is great code” they should be fired.

Anyway… generally speaking, using try/catch blocks is not a great idea.  There are a myriad of reasons but it’s usually something along the lines of:

If you truly have an unexpected error it’s better to let the program crash and then fix the bug.

If you do have to use the try/catch exception handling block, you should only catch explicit exceptions.  For example catch a file access exception or a database invalid primary key exception.  Just catching the generic exception is poor practice.

There’s another reason to avoid try/catch though… it is a performance hog.

Well… performance HOG might be a bit of an exaggeration.  I had to go to great lengths to illustrate this.

I created two tests… each one writes 24 lines to a text file a number of times.  The tests both write the file line by line.  In the first test, the lines are written out with no try/catch block.  Something like this:

 public static void Execute()
        {
            string[] lines = { "Alpha", "Beta", "Gamma", "Delta", "Epsilon", "Zeta", "Eta", "Theta", "Iota", "Kappa", "Lambda", "Mu", "Nu", "Xi", "Omicron", "Pi", "Rho", "Sigma", "Tau", "Upsilon", "Phi", "Chi", "Psi", "Omega" };
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Mark\Desktop\execute10.txt"))
            {
                file.WriteLine(lines[0]);
                file.WriteLine(lines[1]);
                file.WriteLine(lines[2]);
                // write out all 24 array elements 10 times
            }
        }

It iterates through the array, writing all 24 entries in the array 10 times for a total of 240 lines.

 

In the second test, I do exactly the same thing except I wrap every single thing in a try/catch block. It looks like this:

 public static void ExecuteTryCatch()
        {
            try
            {
                string[] lines = { "Alpha", "Beta", "Gamma", "Delta", "Epsilon", "Zeta", "Eta", "Theta", "Iota", "Kappa", "Lambda", "Mu", "Nu", "Xi", "Omicron", "Pi", "Rho", "Sigma", "Tau", "Upsilon", "Phi", "Chi", "Psi", "Omega" };
                try
                {
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Mark\Desktop\executetrycatch10.txt"))
                    {
                        try { file.WriteLine(lines[0]); }
                        catch { }
                        try { file.WriteLine(lines[1]); }
                        catch { }
                        try { file.WriteLine(lines[2]); }
                        catch { }
                        // write out all 24 array elements 10 times
                        // each one wrapped in a try/catch
                    }
                }
                catch { }
            }
            catch
            {

            }
        }

Again, I write each entry out 10 times for a total of 240 lines.  Here are the results from the 10 line execution being run.

10run

After having run the test many times, it usually results in a 2x to 3x performance difference.  Next, I upped it to writing the array 100 times.

100run

 

This yields something closer to a 10x performance difference!  You wanna get nuts?  LET’S GET NUTS!  I ran it again writing each array out 1,000 times.

1000run

135 milliseconds versus 10.8 seconds!  That’s around 80x faster!

Now granted, this was written to illustrate a point.  Nobody would ever do this… would they?  I am in the process of optimizing some code that’s been written by some other people who were just learning.  They have wrapped lots and lots of single lines in try/catch blocks.  We’ll be stripping that stuff out of there.

Also, for what it’s worth, the class I used to write all 24 lines 1,000 times?  Visual Studio doesn’t like dealing with files that big.  The code file itself is over 2mb and over 48,000 lines!  Hahahha.

BigClassFile

BigClassFile2

Here’s one more run showing all six tests.

1110run

 

Straight Writes Writes wrapped in Try/Catch
Iterate 10 times 3 ms 7 ms
Iterate 100 times 22 ms 144 ms
Iterate 1,000 times 287 ms 10,880 ms

Leave a Reply

Scroll To Top