Skip to content

Commit 2f16caa

Browse files
jgarciadelanocedaJavier Garcia de la Noceda Arguellesglennawatson
authored
perf: escape query components in place (#2277)
Escape query components directly into the pooled buffer while preserving framework Unicode behavior. Co-authored-by: Javier Garcia de la Noceda Arguelles <jgarcian@riamoneytransfer.com> Co-authored-by: Glenn Watson <5834289+glennawatson@users.noreply.github.com>
1 parent 5cd9a96 commit 2f16caa

5 files changed

Lines changed: 134 additions & 12 deletions

File tree

‎src/Refit/GeneratedQueryStringBuilder.cs‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ public void AddFlag(string? name, bool preEncoded)
150150
}
151151

152152
AppendSeparator();
153-
_text.Append(preEncoded ? name : StringHelpers.EscapeDataString(name));
153+
AppendQueryComponent(name, preEncoded);
154154
}
155155

156156
/// <summary>Starts a collection-valued parameter fed by <see cref="AddCollectionValue(string?)"/> calls and finished by <see cref="EndCollection"/>.</summary>
@@ -343,9 +343,9 @@ internal void AppendSeparator()
343343
internal void AppendPair(string name, string value, bool keyEscaped, bool preEncoded)
344344
{
345345
AppendSeparator();
346-
_text.Append(keyEscaped || preEncoded ? name : StringHelpers.EscapeDataString(name));
346+
AppendQueryComponent(name, keyEscaped || preEncoded);
347347
_text.Append('=');
348-
_text.Append(preEncoded ? value : StringHelpers.EscapeDataString(value));
348+
AppendQueryComponent(value, preEncoded);
349349
}
350350

351351
#if NET6_0_OR_GREATER
@@ -360,10 +360,28 @@ internal void AppendFormattedPair<T>(string name, T value, string? format, bool
360360
where T : ISpanFormattable
361361
{
362362
AppendSeparator();
363-
_text.Append(keyEscaped || preEncoded ? name : StringHelpers.EscapeDataString(name));
363+
AppendQueryComponent(name, keyEscaped || preEncoded);
364364
_text.Append('=');
365365
AppendFormattedValue(ref _text, value, format, escape: !preEncoded);
366366
}
367367

368368
#endif
369+
370+
/// <summary>Appends one query key or value, percent-encoding directly into the query buffer when required.</summary>
371+
/// <param name="value">The query component to append.</param>
372+
/// <param name="appendVerbatim">Whether the component is already encoded and can be copied verbatim.</param>
373+
private void AppendQueryComponent(string value, bool appendVerbatim)
374+
{
375+
if (appendVerbatim)
376+
{
377+
_text.Append(value);
378+
return;
379+
}
380+
381+
#if NET8_0_OR_GREATER
382+
StringHelpers.AppendUriDataEscaped(ref _text, value.AsSpan());
383+
#else
384+
_text.Append(StringHelpers.EscapeDataString(value));
385+
#endif
386+
}
369387
}

‎src/Refit/StringHelpers.cs‎

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -119,16 +119,17 @@ internal static string RemoveCrOrLf(string value)
119119
}
120120

121121
#if NET8_0_OR_GREATER
122-
/// <summary>Percent-encodes a formatted span per RFC 3986 straight into the target, with no intermediate string.</summary>
122+
/// <summary>Percent-encodes a span per RFC 3986 straight into the target, with no intermediate string.</summary>
123123
/// <param name="target">The buffer receiving the escaped text.</param>
124-
/// <param name="span">The invariant-formatted value to escape.</param>
125-
/// <remarks>Span-formattable values render as ASCII under the invariant culture, which this escapes in place. A
126-
/// non-ASCII character (never produced by the routed value types) defers to the framework escaper so the UTF-8
127-
/// percent-encoding matches <see cref="Uri.EscapeDataString(string)"/> exactly.</remarks>
124+
/// <param name="span">The URI data component to escape.</param>
125+
/// <remarks>ASCII text is escaped in place. A non-ASCII character defers to the framework escaper so UTF-8
126+
/// percent-encoding and invalid-surrogate behavior match <see cref="Uri.EscapeDataString(string)"/> exactly.</remarks>
128127
internal static void AppendUriDataEscaped(ref ValueStringBuilder target, scoped ReadOnlySpan<char> span)
129128
{
130-
foreach (var c in span)
129+
var firstCharacterToEscape = -1;
130+
for (var i = 0; i < span.Length; i++)
131131
{
132+
var c = span[i];
132133
if (c > MaxAsciiChar)
133134
{
134135
#if NET9_0_OR_GREATER
@@ -138,10 +139,23 @@ internal static void AppendUriDataEscaped(ref ValueStringBuilder target, scoped
138139
#endif
139140
return;
140141
}
142+
143+
if (firstCharacterToEscape < 0 && !IsUriUnreserved(c))
144+
{
145+
firstCharacterToEscape = i;
146+
}
147+
}
148+
149+
if (firstCharacterToEscape < 0)
150+
{
151+
target.Append(span);
152+
return;
141153
}
142154

143-
foreach (var c in span)
155+
target.Append(span[..firstCharacterToEscape]);
156+
for (var i = firstCharacterToEscape; i < span.Length; i++)
144157
{
158+
var c = span[i];
145159
if (IsUriUnreserved(c))
146160
{
147161
target.Append(c);

‎src/Refit/ValueStringBuilder.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,7 @@ internal void Append(char c, int count)
277277

278278
/// <summary>Appends the characters of a span to the builder.</summary>
279279
/// <param name="value">The characters to append.</param>
280-
internal void Append(ReadOnlySpan<char> value)
280+
internal void Append(scoped ReadOnlySpan<char> value)
281281
{
282282
var pos = _pos;
283283
if (pos > _chars.Length - value.Length)
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// Copyright (c) 2019-2026 ReactiveUI and Contributors. All rights reserved.
2+
// ReactiveUI and Contributors licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for full license information.
4+
5+
using System.Diagnostics.CodeAnalysis;
6+
using BenchmarkDotNet.Attributes;
7+
using BenchmarkDotNet.Configs;
8+
using BenchmarkDotNet.Diagnosers;
9+
10+
namespace Refit.Benchmarks;
11+
12+
/// <summary>Compares the chained concatenation and interpolated-string forms emitted for nested query-object keys.</summary>
13+
/// <remarks>The inputs mirror generated code: the parent key is known only at runtime, while the delimiter, property
14+
/// prefix, alias, and CLR property name are compile-time literals.</remarks>
15+
[MemoryDiagnoser]
16+
[EventPipeProfiler(EventPipeProfile.GcVerbose)]
17+
[ShortRunJob]
18+
[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
19+
[CategoriesColumn]
20+
public class NestedQueryKeyCompositionBenchmarks
21+
{
22+
/// <summary>The compile-time delimiter and property prefix emitted before a nested property name.</summary>
23+
private const string NestedPrefix = ".billing-";
24+
25+
/// <summary>The compile-time CLR property name passed to the key formatter.</summary>
26+
private const string PropertyName = "PostalCode";
27+
28+
/// <summary>The runtime key of the enclosing query object.</summary>
29+
private readonly string _parentKey = "customer";
30+
31+
/// <summary>Settings used by the key-formatter path.</summary>
32+
private readonly RefitSettings _settings = new();
33+
34+
/// <summary>Builds an aliased nested key using the current generated concatenation.</summary>
35+
/// <returns>The composed query key.</returns>
36+
[Benchmark(Baseline = true)]
37+
[BenchmarkCategory("Alias")]
38+
[SuppressMessage("Roslynator", "RCS1190", Justification = "The benchmark intentionally measures the generated concatenation shape.")]
39+
[SuppressMessage("Style", "SST2249", Justification = "The benchmark intentionally measures the generated concatenation shape.")]
40+
public string ConcatenationAlias() => _parentKey + NestedPrefix + "postal_code";
41+
42+
/// <summary>Builds an aliased nested key using the proposed generated interpolation.</summary>
43+
/// <returns>The composed query key.</returns>
44+
[Benchmark]
45+
[BenchmarkCategory("Alias")]
46+
public string InterpolationAlias() => $"{_parentKey}.billing-postal_code";
47+
48+
/// <summary>Builds a pre-escaped nested CLR-name key using the current generated concatenation.</summary>
49+
/// <returns>The composed query key.</returns>
50+
[Benchmark(Baseline = true)]
51+
[BenchmarkCategory("PreEscaped")]
52+
[SuppressMessage("Roslynator", "RCS1190", Justification = "The benchmark intentionally measures the generated concatenation shape.")]
53+
[SuppressMessage("Style", "SST2249", Justification = "The benchmark intentionally measures the generated concatenation shape.")]
54+
public string ConcatenationPreEscaped() => _parentKey + NestedPrefix + PropertyName;
55+
56+
/// <summary>Builds a pre-escaped nested CLR-name key using the proposed generated interpolation.</summary>
57+
/// <returns>The composed query key.</returns>
58+
[Benchmark]
59+
[BenchmarkCategory("PreEscaped")]
60+
public string InterpolationPreEscaped() => $"{_parentKey}.billing-PostalCode";
61+
62+
/// <summary>Builds the nested prefix passed to the key formatter using the current generated concatenation.</summary>
63+
/// <returns>The formatted query key.</returns>
64+
[Benchmark(Baseline = true)]
65+
[BenchmarkCategory("Formatted")]
66+
[SuppressMessage("Style", "SST2249", Justification = "The benchmark intentionally measures the generated concatenation shape.")]
67+
public string ConcatenationFormatted() =>
68+
GeneratedRequestRunner.BuildQueryKey(_settings, PropertyName, null, _parentKey + NestedPrefix);
69+
70+
/// <summary>Builds the nested prefix passed to the key formatter using the proposed generated interpolation.</summary>
71+
/// <returns>The formatted query key.</returns>
72+
[Benchmark]
73+
[BenchmarkCategory("Formatted")]
74+
public string InterpolationFormatted() =>
75+
GeneratedRequestRunner.BuildQueryKey(_settings, PropertyName, null, $"{_parentKey}.billing-");
76+
}

‎src/tests/Refit.Tests/GeneratedQueryStringBuilderTests.cs‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,20 @@ public async Task AddOmitsParameterForNullValue()
3939
await Assert.That(result).IsEqualTo(Path);
4040
}
4141

42+
/// <summary>Verifies escaped keys and values match the framework for reserved ASCII and non-ASCII text.</summary>
43+
/// <returns>A task representing the asynchronous test.</returns>
44+
[Test]
45+
public async Task AddEscapesKeyAndValueLikeFramework()
46+
{
47+
const string name = "filter name/café";
48+
const string value = "tea & café 🍵";
49+
var builder = new GeneratedQueryStringBuilder(Path);
50+
builder.Add(name, value, false);
51+
52+
var expected = $"{Path}?{Uri.EscapeDataString(name)}={Uri.EscapeDataString(value)}";
53+
await Assert.That(builder.Build()).IsEqualTo(expected);
54+
}
55+
4256
/// <summary>Verifies a null flag name omits the flag, leaving the path unchanged.</summary>
4357
/// <returns>A task representing the asynchronous test.</returns>
4458
[Test]

0 commit comments

Comments
 (0)
⌂ 换网址