Speed Improvement by avoiding exceptions


I learned a neat thing.  If you press ctrl-alt-e in Visual Studio you bring up this dialog:

Exceptions Dialog

Then check the Thrown checkbox for "Common Language Runtime Exceptions" like this:

Exceptions Dialog with CLR Exceptions Checked

Then run the project in debug mode and if an exception occurs the run will break at that point in the code and you can examine what happened.  This is great for finding uncaught exceptions and improper use of exceptions like this:

                Try
                    If c.Contains("somestring") Then Stop
                Catch ex As NullReferenceException
                End Try

One should never do this because it is extremely inefficient.  Exceptions are costly and should always be avoided if possible.  In this case we can avoid this exception by checking c for nothing, like so:

            If Not IsNothing(c) Then
                If c.Contains("somestring") Then Stop
            End If

No comments:

Post a Comment