Skip to content

Commit ab31619

Browse files
committed
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.
1 parent 5ff2399 commit ab31619

File tree

1 file changed

+39
-9
lines changed

1 file changed

+39
-9
lines changed

src/Http/Http.Extensions/src/UriHelper.cs

Lines changed: 39 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -210,18 +210,48 @@ public static string GetDisplayUrl(this HttpRequest request)
210210
var path = request.Path.Value ?? string.Empty;
211211
var queryString = request.QueryString.Value ?? string.Empty;
212212

213-
// PERF: Calculate string length to allocate correct buffer size for StringBuilder.
214213
var length = scheme.Length + SchemeDelimiter.Length + host.Length
215214
+ pathBase.Length + path.Length + queryString.Length;
216215

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();
216+
return string.Create(
217+
length,
218+
(scheme, host, pathBase, path, queryString),
219+
static (buffer, uriParts) =>
220+
{
221+
var (scheme, host, pathBase, path, queryString) = uriParts;
222+
223+
if (scheme.Length > 0)
224+
{
225+
scheme.CopyTo(buffer);
226+
buffer = buffer.Slice(scheme.Length);
227+
}
228+
229+
SchemeDelimiter.CopyTo(buffer);
230+
buffer = buffer.Slice(SchemeDelimiter.Length);
231+
232+
if (host.Length > 0)
233+
{
234+
host.CopyTo(buffer);
235+
buffer = buffer.Slice(host.Length);
236+
}
237+
238+
if (pathBase.Length > 0)
239+
{
240+
pathBase.CopyTo(buffer);
241+
buffer = buffer.Slice(pathBase.Length);
242+
}
243+
244+
if (path.Length > 0)
245+
{
246+
path.CopyTo(buffer);
247+
buffer = buffer.Slice(path.Length);
248+
}
249+
250+
if (queryString.Length > 0)
251+
{
252+
queryString.CopyTo(buffer);
253+
}
254+
});
225255
}
226256

227257
/// <summary>

0 commit comments

Comments
 (0)