1

Closed

[perf] System.net.Http.Formatting.ReadAsAsync

description

From a user -

When using the following in a client scenario
var item = await content.ReadAsAsync<TestData>();
The call may take 100s of milliseconds for the first call, and subsequently the same on every call.

but if you precreate the JsonMediaTypeFormatter and call
var item = await content.ReadAsAsync<TestData>(new [] { JsonMediaTypeFormatter } );
The first call will still be expensive but the following calls will be sub-millisecond.

I reproduced the issue, and it comes down to the fact that the contractresolver is not being cached when we new up a new formatter, I'm attaching a sample that shows the timing based on what is being cached.

Unfortunately if we start caching the contractresolver across serializer instances, we introduce a breaking change behavior when the contract is different per serializer.

We can consider however caching the JsonMediaTypeFormatter in a static for this method calls only.

file attachments

comments

yishaigalatzer wrote Aug 13, 2014 at 10:44 PM

We can fix this by create a static variable holding on to the new formatter collection created at the first call.

However we have to be 100% sure that user code cannot interact and change the formatters, and that the formatters are completely stateless.