• Frugal Cafe
  • Posts
  • FC17 Real world example of not reusing JSON contract resolver

FC17 Real world example of not reusing JSON contract resolver

Now you can see their cost for real

In FC13 Reuse contract resolver objects (beehiiv.com), we discussed the importance of reusing JSON contract resolver objects. Today, I found a real-world example of not reusing contract resolver objects.

This is found in Visual Studio 2022 ServiceHub.Host.AnyCPU process. Here is allocation stack:

TryGetArgumentByNameOrIndex is responsible for 42% of total allocations in the process. There are large numbers of allocations coming from MarshalContractResolver.ResolveContract, mostly for reflection calls for creating new contracts.

Here is MarshalContractResolver constructor:

Allocating DefaultContractResolver is the wrong thing to do, unless this is singleton object.

Here is caller source code:

Again, this is the wrong way to do business, unless JsonMessageFormatter is singleton.

A single allocation sample is found:

So this does not look like singleton object.

Now let’s check CPU stacks:

20.9% in ResolveContract. Expensive lawyers are hired to write the same contracts over and over again.

Now let’s check JIT events:

It looks this code path is executed 34 times in 7 second interval. This shows the cost of not reusing JSON contract resolver for real. Once this issue is fixed, the code will be much faster.