When I'm profiling solutions I work on, many times one of the first bottlenecks I come across is tracing code - even if tracing is currently turned off in the solution! The reason for this is how the solution checks to determine whether to generate tracing output.

Everyone knows that tracing is expensive and should only be generated if you're currently trying to debug the solution, so the classic (very simple) pattern for implementing tracing is something like this:

if (TracingFlag == True)

{

      GenerateTracingOutput("It's all going wrong here");

}

The problem is where you go to get the value of "TracingFlag" and how often you get it. Invariably the value is stored as part of the solutions configuration somewhere, either in the registry or an XML config file, which is fine. What isn't fine is to reread this value from the registry or file every single time you need to determine whether or not to trace. The classic reasons for doing this are: Laziness, registry access is 'free' (yeah right) or I want to dynamically control tracing so I need to keep re-reading the value.

Taking these in turn:

Laziness - how hard is it to create a static variable to cache the tracing flag?

Registry access is 'free' - Registry access isn't that fast. It requires a transition to the kernel and is protected by a global lock which means if all your threads are constantly reading the tracing flag they all end up getting serialised. You really need to read it once and cache that value.

Dynamic tracing - From my experience being able to dynamically control tracing on a solution is a nice to have that is actually rarely used in the real world. However if you really need think you need it then don't reread it from source each time but read it once, cache it and then setup a ChangeNotificationRequest on the file or registry key so you can re-read the flag if it ever gets changed.

Another classic performance hit with tracing is to implement a tracing class and then instantiate an instance of the class everytime you want to check for tracing because the trace flag is a member of the class... Don't do it! Either make your tracing class a static class or instantiate an instance at startup and cache it.