FC43: Anti-Pattern - Trace to nowhere

Generating expensive tracing message when tracing is not enabled

Tracing is a common source of performance issues in cloud services because people like to add tons of tracing to be able to troubleshoot cloud services they can’t touch manually. A simple anti-pattern is called trace to nowhere.

Here is a sample stack found in Visual Studio:

ProcessEvent method is causing 0.5% allocations due to object array allocation and flag enum to string conversion. The latter is implemented using StringBuilder.

Source code:

Implementation:

This is already a quite good tracing API design, deferring string formatting until the final message is really needed. But the caller is still paying for flag enum to string conversion, and object array allocation.

The best way to avoid all unnecessary allocations is to check if tracing level is enabled before making the call. It’s possible here because IsTracing is a public method. The flag enum to string conversion can be avoided by remove the ToString call, you’re just paying for boxing.

There are much more expensive trace to nowhere calls found in production. For example, people do expensive JSON serialization, add extra formatting or trimming.

If you have extensive tracing/logging in your cloud services or applications, capture traces to find such call stacks. They’re normally related to string.Format or StringBuilder.