Reduce allocations in CookieContainer.GetCookieHeader#7285
Reduce allocations in CookieContainer.GetCookieHeader#7285stephentoub merged 2 commits intodotnet:masterfrom
Conversation
HttpClient defaults to UseCookies=true, which means by default every request ends up asking the CookieContainer to get the cookie header that should be used. Today, even if there aren't any cookies for the Uri, this ends up allocating a CookieCollection, a StringBuilder, a couple of List<T>s, an iterator, etc., none of which are actually necessary. And if there are cookies for the Uri, the serialization of each cookie results in a handful of strings, char[]s, and string[] allocations. This commit fixes the implementation to avoid these. (There are still some that could be cleaned up with further work, but it becomes much more invasive.)
| @@ -2,10 +2,11 @@ | |||
| // The .NET Foundation licenses this file to you under the MIT license. | |||
There was a problem hiding this comment.
You should consider making equivalent changes to the copy of Cookie.cs here:
https://github.com/dotnet/corefx/blob/master/src/System.Net.Http/src/netcore50/System/Net/cookie.cs
Long term....there won't be a copy of the file. But due to the way that netcore50 needs cookie functionality, it needed to duplicate the file for now....could potentially be refactored to common code, etc.
Per PR feedback.
|
Thanks, @davidsh. I ported the Cookie changes over to cookie.cs. I decided not to use StringBuilderCache (yet), since it's not currently used in the Http library, but that's something we likely want to do for other reasons soon. |
|
LGTM |
|
Thanks, @davidsh. Do you want to run any .NET Native tests before this is merged? |
|
I'm ok w/ merging now. |
Reduce allocations in CookieContainer.GetCookieHeader Commit migrated from dotnet/corefx@f22362d
HttpClient defaults to UseCookies=true, which means by default every request ends up asking the CookieContainer to get the cookie header that should be used. Today, even if there aren't any cookies for the given Uri, this ends up doing a lot of allocation. And if there are cookies for the Uri, the serialization of each cookie results in a handful of strings, char[]s, and string[] allocations. This commit tweaks the implementation to avoid a bunch of these, including taking advantage of StringBuilderCache. (There are still some more that could be cleaned up with further work, but it becomes much more invasive.)
For this sample program:
before these changes, I see the following allocations:


and after thes changes:
If I then change the GetCookieHeader line to be:
before these changes, I see the following allocations:


and after these changes:
cc: @davidsh, @CIPop, @ericeil