Skip to content

Commit 1867e51

Browse files
Improve performance of UriHelper.GetDisplayUrl (#55611)
* Optimized string concatenation with `string.Create` Replaced `StringBuilder` concatenation with the more efficient `string.Create` method for creating new strings by concatenating `scheme`, `host`, `pathBase`, `path`, and `queryString`. This method reduces overhead by avoiding multiple string concatenations and allocating the correct buffer size for the new string. The `CopyTo` method is used in a callback function to copy each string to the new string, slicing the buffer to remove the copied part. The `SchemeDelimiter` is always copied to the new string, regardless of its length. This change enhances the performance of the code. * changed to string.Concat(params ReadOnlySpan<string?>) * Update src/Http/Http.Extensions/src/UriHelper.cs --------- Co-authored-by: Stephen Halter <halter73@gmail.com>
1 parent 49df2e6 commit 1867e51

File tree

1 file changed

+1
-19
lines changed

1 file changed

+1
-19
lines changed

Diff for: src/Http/Http.Extensions/src/UriHelper.cs

+1-19
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
using System.Buffers;
55
using System.Diagnostics.CodeAnalysis;
66
using System.Runtime.CompilerServices;
7-
using System.Text;
87

98
namespace Microsoft.AspNetCore.Http.Extensions;
109

@@ -204,24 +203,7 @@ public static string GetEncodedPathAndQuery(this HttpRequest request)
204203
/// suitable only for display.</returns>
205204
public static string GetDisplayUrl(this HttpRequest request)
206205
{
207-
var scheme = request.Scheme ?? string.Empty;
208-
var host = request.Host.Value ?? string.Empty;
209-
var pathBase = request.PathBase.Value ?? string.Empty;
210-
var path = request.Path.Value ?? string.Empty;
211-
var queryString = request.QueryString.Value ?? string.Empty;
212-
213-
// PERF: Calculate string length to allocate correct buffer size for StringBuilder.
214-
var length = scheme.Length + SchemeDelimiter.Length + host.Length
215-
+ pathBase.Length + path.Length + queryString.Length;
216-
217-
return new StringBuilder(length)
218-
.Append(scheme)
219-
.Append(SchemeDelimiter)
220-
.Append(host)
221-
.Append(pathBase)
222-
.Append(path)
223-
.Append(queryString)
224-
.ToString();
206+
return string.Concat([request.Scheme, SchemeDelimiter, request.Host.Value, request.PathBase.Value, request.Path.Value, request.QueryString.Value]);
225207
}
226208

227209
/// <summary>

0 commit comments

Comments
 (0)