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

Published 02 February 08 01:19 by alikl

Comments

# ACE Team - Security, Performance & Privacy said on March 11, 2008 4:53 PM:

How to anticipate or better off avoid performance related "surprises" during load and stress

# Alik Levin - Life At Microsoft said on April 8, 2008 7:32 AM:

[Ed. - Guy, apologies for originally calling you Eran.. *shy*] PDD - Performance Driven Development presentation

# Alik Levin's said on April 28, 2008 8:31 AM:

Chatty database access is the surefire way for slow performance caused by  resources starvation

# Alik Levin's said on May 2, 2008 9:12 AM:

Serving images dynamically may cause performance hit. Dynamically served images require more HTTP requests

New Comments to this post are disabled

Search

This Blog

. My Personal Blog .

.Net Performance How To's

.Net Security How To's

Design Patterns

Impactful

Lifecycle Phases

Popular

Tools

Syndication

Page view tracker