Skip to content

Avoid url string allocation in WebProxy.IsMatchInBypassList #73807

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

Merged
merged 2 commits into from
Aug 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
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 @@ -10,6 +10,7 @@
<Compile Condition="'$(TargetPlatformIdentifier)' != 'Browser'" Include="System\Net\WebProxy.NonBrowser.cs" />
</ItemGroup>
<ItemGroup>
<Reference Include="System.Memory" />
<Reference Include="System.Net.NameResolution" />
<Reference Include="System.Net.NetworkInformation" />
<Reference Include="System.Net.Primitives" />
Expand Down
26 changes: 19 additions & 7 deletions src/libraries/System.Net.WebProxy/src/System/Net/WebProxy.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Buffers;
using System.Collections;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.Serialization;
Expand Down Expand Up @@ -154,16 +156,26 @@ private bool IsMatchInBypassList(Uri input)
{
UpdateRegexList(canThrow: false);

if (_regexBypassList != null)
if (_regexBypassList is Regex[] bypassList)
{
Span<char> stackBuffer = stackalloc char[128];
string matchUriString = input.IsDefaultPort ?
string.Create(null, stackBuffer, $"{input.Scheme}://{input.Host}") :
string.Create(null, stackBuffer, $"{input.Scheme}://{input.Host}:{(uint)input.Port}");
bool isDefaultPort = input.IsDefaultPort;
int lengthRequired = input.Scheme.Length + 3 + input.Host.Length;
if (!isDefaultPort)
{
lengthRequired += 1 + 5; // 1 for ':' and 5 for max formatted length of a port (16 bit value)
}

int charsWritten;
Span<char> url = lengthRequired <= 256 ? stackalloc char[256] : new char[lengthRequired];
bool formatted = isDefaultPort ?
url.TryWrite($"{input.Scheme}://{input.Host}", out charsWritten) :
url.TryWrite($"{input.Scheme}://{input.Host}:{(uint)input.Port}", out charsWritten);
Debug.Assert(formatted);
url = url.Slice(0, charsWritten);

foreach (Regex r in _regexBypassList)
foreach (Regex r in bypassList)
{
if (r.IsMatch(matchUriString))
if (r.IsMatch(url))
{
return true;
}
Expand Down