Repository navigation
Expand file tree
/
Copy pathStringBuilderCache.cs
More file actions
82 lines (75 loc) · 2.74 KB
/
Copy pathStringBuilderCache.cs
File metadata and controls
82 lines (75 loc) · 2.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using System;
using System.Text;
using System.Threading;
namespace Opserver
{
/// <summary>
/// Provides optimized access to StringBuilder instances
/// Credit: Marc Gravell (@marcgravell), Stack Exchange Inc.
/// </summary>
public static class StringBuilderCache
{
// one per thread
[ThreadStatic]
private static StringBuilder _perThread;
// and one secondary that is shared between threads
private static StringBuilder _shared;
private const int DefaultCapacity = 0x10;
/// <summary>
/// Obtain a StringBuilder instance; this could be a recycled instance, or could be new
/// </summary>
/// <param name="capacity">The capaity to start the fetched <see cref="StringBuilder"/> at.</param>
public static StringBuilder Get(int capacity = DefaultCapacity)
{
var tmp = _perThread;
if (tmp != null)
{
_perThread = null;
tmp.Length = 0;
return tmp;
}
tmp = Interlocked.Exchange(ref _shared, null);
if (tmp == null) return new StringBuilder(capacity);
tmp.Length = 0;
return tmp;
}
/// <summary>
/// Get the string contents of a StringBuilder and recyle the instance at the same time
/// </summary>
/// <param name="builder">The <see cref="StringBuilder"/> to recycle.</param>
public static string ToStringRecycle(this StringBuilder builder)
{
var s = builder.ToString();
Recycle(builder);
return s;
}
/// <summary>
/// Get the string contents of a StringBuilder and recycle the instance at the same time
/// </summary>
/// <param name="builder">The <see cref="StringBuilder"/> to recycle.</param>
/// <param name="startIndex">The index to start at.</param>
/// <param name="length">The amount of characters to get.</param>
public static string ToStringRecycle(this StringBuilder builder, int startIndex, int length)
{
var s = builder.ToString(startIndex, length);
Recycle(builder);
return s;
}
/// <summary>
/// Recycles a StringBuilder instance if possible
/// </summary>
/// <param name="builder">The <see cref="StringBuilder"/> to recycle.</param>
public static void Recycle(StringBuilder builder)
{
if (builder == null) return;
if (_perThread == null)
{
_perThread = builder;
}
else
{
Interlocked.CompareExchange(ref _shared, builder, null);
}
}
}
}