Skip to content

Commit d6b2446

Browse files
Pool string builders when rendering to a string (#77)
1 parent 2d4b4ff commit d6b2446

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

src/Directory.Build.props

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<Project>
22

33
<PropertyGroup>
4-
<VersionPrefix>0.9.0</VersionPrefix>
4+
<VersionPrefix>0.9.1</VersionPrefix>
55
<!-- VersionSuffix used for local builds -->
66
<VersionSuffix>dev</VersionSuffix>
77
<!-- VersionSuffix to be used for CI builds -->

src/RazorSlices/RazorSlice.StringBuilderExtensions.cs

+13-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System.Text;
22
using System.Text.Encodings.Web;
3+
using Microsoft.Extensions.ObjectPool;
34

45
namespace RazorSlices;
56

@@ -8,6 +9,9 @@ namespace RazorSlices;
89
/// </summary>
910
public static class RazorSliceStringBuilderExtensions
1011
{
12+
// Pooled builders are initialized with a capacity of 256 & only kept if their capacity <=4096 chars when returned to the pool
13+
private static readonly ObjectPool<StringBuilder> _stringBuilderPool = new DefaultObjectPoolProvider().CreateStringBuilderPool(256, 4 * 1024);
14+
1115
/// <summary>
1216
/// Renders the template to the specified <see cref="StringBuilder"/>.
1317
/// </summary>
@@ -31,15 +35,17 @@ public static ValueTask RenderAsync(this RazorSlice slice, StringBuilder stringB
3135
/// <returns>The template rendered to a <see cref="string"/>.</returns>
3236
public static ValueTask<string> RenderAsync(this RazorSlice slice, HtmlEncoder? htmlEncoder = null, CancellationToken cancellationToken = default)
3337
{
34-
var sb = new StringBuilder();
38+
var sb = _stringBuilderPool.Get();
3539
var task = slice.RenderAsync(sb, htmlEncoder, cancellationToken);
3640

3741
if (task.IsCompletedSuccessfully)
3842
{
3943
#pragma warning disable CA1849 // Call async methods when in an async method: task is already completed
4044
task.GetAwaiter().GetResult();
4145
#pragma warning restore CA1849
42-
return ValueTask.FromResult(sb.ToString());
46+
var result = sb.ToString();
47+
_stringBuilderPool.Return(sb);
48+
return ValueTask.FromResult(result);
4349
}
4450

4551
return AwaitRenderTask(task, sb);
@@ -48,6 +54,10 @@ public static ValueTask<string> RenderAsync(this RazorSlice slice, HtmlEncoder?
4854
private static async ValueTask<string> AwaitRenderTask(ValueTask task, StringBuilder sb)
4955
{
5056
await task;
51-
return sb.ToString();
57+
58+
var result = sb.ToString();
59+
_stringBuilderPool.Return(sb);
60+
61+
return result;
5262
}
5363
}

0 commit comments

Comments
 (0)