Share via


Performance Sin - Using Exceptions To Control Flow

Want to spot coding anti-patterns from performance perspective without actually looking in the code?

One of the common performance coding anti-patterns I’ve noticed lately is using Exception Handling to control program flow.

The anti-patterns

Most common anti-pattern is just using exception handling to control flow, in some cases it was even nested exception handling – that means the exception is thrown anyway.

In other cases there were empty “catch” exception statements. That means that precious cycles .Net consumes to handle the exception spent for nothing.

The last case was where exception handling was done to catch simple types parsing. That was done on each request.

How to identify Exception Handling anti-pattern

To identify exception handling anti-pattern set “.NET CLR Exceptions/# of Excepts Thrown” perf counter. If you see the graph constantly climbs on each request chance are Exception Handling is used to control the flow which is performance anti-pattern:

clip_image002

Look at the relevant source code to spot try/catch blocks. If the source code is not available use Reflector to reverse engineer the compiled assemblies into C# sources – I used it very successfully during my latest performance review.

Best practices

Do not use exception handling to control the flow. Try to reduce catching exceptions to only most upper component/class. Catching exceptions is expensive from both CPU and memory perspective.

Use TryParse method instead Parse method to avoid throwing exceptions .

Use simple "if" statement to check for nulls.

Tools

Use perfmon to spot the anti-pattern with Exception handling. Run perfmon in command line and add “.NET CLR Exceptions/# of Excepts Thrown” counter. Then run few scenarios to see the graph.

Use Practice Checker for static code analysis. The tool scans the code and reveals excessive usage of exception handling.

My related posts

Comments

  • Anonymous
    March 11, 2008
    How to anticipate or better off avoid performance related "surprises" during load and stress
  • Anonymous
    April 07, 2008
    [Ed. - Guy, apologies for originally calling you Eran.. shy] PDD - Performance Driven Development presentation
  • Anonymous
    April 28, 2008
    Chatty database access is the surefire way for slow performance caused by  resources starvation
  • Anonymous
    May 02, 2008
    Serving images dynamically may cause performance hit. Dynamically served images require more HTTP requests