Skip to content

Commit cef8841

Browse files
committed
Remove some allocs
1 parent 05ad458 commit cef8841

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

src/Benchmarks/Middleware/MiddlewareHelpers.cs

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
// Copyright (c) .NET Foundation. All rights reserved.
22
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
33

4+
using System;
5+
using System.Buffers;
46
using System.Collections.Generic;
57
using System.Globalization;
68
using System.Text;
@@ -37,12 +39,14 @@ public static Task RenderFortunesHtml(IEnumerable<Fortune> model, HttpContext ht
3739

3840
var sb = StringBuilderCache.Acquire();
3941
sb.Append("<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>");
42+
43+
Span<char> buffer = stackalloc char[256];
4044
foreach (var item in model)
4145
{
4246
sb.Append("<tr><td>");
43-
sb.Append(item.Id.ToString(CultureInfo.InvariantCulture));
47+
sb.Append(CultureInfo.InvariantCulture, $"{item.Id}");
4448
sb.Append("</td><td>");
45-
sb.Append(htmlEncoder.Encode(item.Message));
49+
Encode(sb, htmlEncoder, item.Message);
4650
sb.Append("</td></tr>");
4751
}
4852

@@ -51,6 +55,18 @@ public static Task RenderFortunesHtml(IEnumerable<Fortune> model, HttpContext ht
5155
// fortunes includes multibyte characters so response.Length is incorrect
5256
httpContext.Response.ContentLength = Encoding.UTF8.GetByteCount(response);
5357
return httpContext.Response.WriteAsync(response);
58+
59+
static void Encode(StringBuilder sb, HtmlEncoder htmlEncoder, string item)
60+
{
61+
Span<char> buffer = stackalloc char[256];
62+
int remaining = item.Length;
63+
do
64+
{
65+
htmlEncoder.Encode(item.AsSpan()[..remaining], buffer, out var consumed, out var written, isFinalBlock: true);
66+
remaining -= consumed;
67+
sb.Append(buffer.Slice(0, written));
68+
} while (remaining != 0);
69+
}
5470
}
5571
}
5672
}

0 commit comments

Comments
 (0)