FC74: DevToolsProxy

Got a trace someone asking for performance analysis, here is an interesting stack found in a Microsoft process:

DevToolsProxy.Send is responsible for 37.4% of total allocations, with lots of LOH allocations.

Source code:

This is bad code for the following reasons:

  1. string is formatted first and then passed to the logging method. The input JSON object is converted to string, even when logging is disabled.

  2. On the second line, the JSON object is converted to string again, causing LOH allocation.

  3. The string is then converted to byte array in Utf8 encoding, causing more LOH allocations.

Here is proper implementation:

  1. Check if logging is really enabled before generating new string.

  2. Serialize JSON data into MemoryStream without converting to string first.

  3. Direct send out from the buffer of MemoryStream without causing a byte array allocation.

  4. Try to reuse the MemoryStream.

With proper implementation, most LOH allocation should be avoided in normal case.

Here are most expensive methods by exclusive CPU samples:

The biggest issue is that the process is running in server GC mode on a 20 core machine, when managed heap is only 87 mb. There is no need to run in server GC mode at all.