1
1
using System . Text ;
2
2
using System . Text . Encodings . Web ;
3
+ using Microsoft . Extensions . ObjectPool ;
3
4
4
5
namespace RazorSlices ;
5
6
@@ -8,6 +9,9 @@ namespace RazorSlices;
8
9
/// </summary>
9
10
public static class RazorSliceStringBuilderExtensions
10
11
{
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
+
11
15
/// <summary>
12
16
/// Renders the template to the specified <see cref="StringBuilder"/>.
13
17
/// </summary>
@@ -31,15 +35,17 @@ public static ValueTask RenderAsync(this RazorSlice slice, StringBuilder stringB
31
35
/// <returns>The template rendered to a <see cref="string"/>.</returns>
32
36
public static ValueTask < string > RenderAsync ( this RazorSlice slice , HtmlEncoder ? htmlEncoder = null , CancellationToken cancellationToken = default )
33
37
{
34
- var sb = new StringBuilder ( ) ;
38
+ var sb = _stringBuilderPool . Get ( ) ;
35
39
var task = slice . RenderAsync ( sb , htmlEncoder , cancellationToken ) ;
36
40
37
41
if ( task . IsCompletedSuccessfully )
38
42
{
39
43
#pragma warning disable CA1849 // Call async methods when in an async method: task is already completed
40
44
task . GetAwaiter ( ) . GetResult ( ) ;
41
45
#pragma warning restore CA1849
42
- return ValueTask . FromResult ( sb . ToString ( ) ) ;
46
+ var result = sb . ToString ( ) ;
47
+ _stringBuilderPool . Return ( sb ) ;
48
+ return ValueTask . FromResult ( result ) ;
43
49
}
44
50
45
51
return AwaitRenderTask ( task , sb ) ;
@@ -48,6 +54,10 @@ public static ValueTask<string> RenderAsync(this RazorSlice slice, HtmlEncoder?
48
54
private static async ValueTask < string > AwaitRenderTask ( ValueTask task , StringBuilder sb )
49
55
{
50
56
await task ;
51
- return sb . ToString ( ) ;
57
+
58
+ var result = sb . ToString ( ) ;
59
+ _stringBuilderPool . Return ( sb ) ;
60
+
61
+ return result ;
52
62
}
53
63
}
0 commit comments