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.
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:
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.
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.
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