Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NameValueCollection.ToQueryString performance optimisation #4952

Merged
merged 2 commits into from
Aug 13, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,17 @@ internal static string ToQueryString(this NameValueCollection nv)
var maxLength = 1 + nv.AllKeys.Length - 1; // account for '?', and any required '&' chars
foreach (var key in nv.AllKeys)
{
maxLength += 1 + (key.Length + nv[key]?.Length ?? 0) * 3; // '=' char + worst case assume all key/value chars are escaped
var bytes = Encoding.UTF8.GetByteCount(key) + Encoding.UTF8.GetByteCount(nv[key] ?? string.Empty);
var maxEncodedSize = bytes * 3; // worst case, assume all bytes are URL escaped to 3 chars
maxLength += 1 + maxEncodedSize; // '=' + encoded chars
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the 1 character padding could potentially 0 when nv[key] is empty. Since we don't write =. Not worth the conditional and added complexity though!

}

// prefer stack allocated array for short lengths
// note: renting for larger lengths is slightly more efficient since no zeroing occurs
char[] rentedFromPool = null;
var buffer = maxLength > MaxCharsOnStack
? rentedFromPool = ArrayPool<char>.Shared.Rent(maxLength)
: stackalloc char[MaxCharsOnStack];
: stackalloc char[maxLength];

try
{
Expand Down
12 changes: 11 additions & 1 deletion tests/Tests/Extensions/NameValueCollectionExtensionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,17 @@ public class NameValueCollectionExtensionsTests
new object[] { new NameValueCollection
{
{ "q", null },
}, "?q" }
}, "?q" },

new object[] { new NameValueCollection
{
{ "emoji", "😅"}
}, "?emoji=%F0%9F%98%85" },

new object[] { new NameValueCollection
{
{ "€", "€"}
}, "?%E2%82%AC=%E2%82%AC" }
};
}
}