| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Diagnostics; |
| | | 5 | | using System.Text; |
| | | 6 | | |
| | | 7 | | namespace System.Reflection.Internal |
| | | 8 | | { |
| | | 9 | | /// <summary> |
| | | 10 | | /// The usage is: |
| | | 11 | | /// var inst = PooledStringBuilder.GetInstance(); |
| | | 12 | | /// var sb = inst.builder; |
| | | 13 | | /// ... Do Stuff... |
| | | 14 | | /// ... sb.ToString() ... |
| | | 15 | | /// inst.Free(); |
| | | 16 | | /// </summary> |
| | | 17 | | internal sealed class PooledStringBuilder |
| | | 18 | | { |
| | 0 | 19 | | public readonly StringBuilder Builder = new StringBuilder(); |
| | | 20 | | private readonly ObjectPool<PooledStringBuilder> _pool; |
| | | 21 | | |
| | 0 | 22 | | private PooledStringBuilder(ObjectPool<PooledStringBuilder> pool) |
| | 0 | 23 | | { |
| | 0 | 24 | | Debug.Assert(pool != null); |
| | 0 | 25 | | _pool = pool; |
| | 0 | 26 | | } |
| | | 27 | | |
| | | 28 | | public int Length |
| | | 29 | | { |
| | 0 | 30 | | get { return this.Builder.Length; } |
| | | 31 | | } |
| | | 32 | | |
| | | 33 | | public void Free() |
| | 0 | 34 | | { |
| | 0 | 35 | | var builder = this.Builder; |
| | | 36 | | |
| | | 37 | | // do not store builders that are too large. |
| | 0 | 38 | | if (builder.Capacity <= 1024) |
| | 0 | 39 | | { |
| | 0 | 40 | | builder.Clear(); |
| | 0 | 41 | | _pool.Free(this); |
| | 0 | 42 | | } |
| | 0 | 43 | | } |
| | | 44 | | |
| | | 45 | | public string ToStringAndFree() |
| | 0 | 46 | | { |
| | 0 | 47 | | string result = this.Builder.ToString(); |
| | 0 | 48 | | this.Free(); |
| | | 49 | | |
| | 0 | 50 | | return result; |
| | 0 | 51 | | } |
| | | 52 | | |
| | | 53 | | // global pool |
| | 0 | 54 | | private static readonly ObjectPool<PooledStringBuilder> s_poolInstance = CreatePool(); |
| | | 55 | | |
| | | 56 | | // if someone needs to create a private pool; |
| | | 57 | | public static ObjectPool<PooledStringBuilder> CreatePool() |
| | 0 | 58 | | { |
| | 0 | 59 | | ObjectPool<PooledStringBuilder>? pool = null; |
| | 0 | 60 | | pool = new ObjectPool<PooledStringBuilder>(() => new PooledStringBuilder(pool!), 32); |
| | 0 | 61 | | return pool; |
| | 0 | 62 | | } |
| | | 63 | | |
| | | 64 | | public static PooledStringBuilder GetInstance() |
| | 0 | 65 | | { |
| | 0 | 66 | | var builder = s_poolInstance.Allocate(); |
| | 0 | 67 | | Debug.Assert(builder.Builder.Length == 0); |
| | 0 | 68 | | return builder; |
| | 0 | 69 | | } |
| | | 70 | | } |
| | | 71 | | } |
| | | 72 | | |