Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nameofSEOKWONHONG/2019ce67870bed0704546413bcd10c76 to your computer and use it in GitHub Desktop.
Save nameofSEOKWONHONG/2019ce67870bed0704546413bcd10c76 to your computer and use it in GitHub Desktop.
StringBuilder pool C#
using System.Text;
using System.Threading;
namespace XLog.Formatters
{
internal static class FixedStringBuilderPool
{
private const int BuildersCount = 10;
private const int BuilderLength = 1000;
private static readonly StringBuilder[] Builders;
private static int _index = -1;
static FixedStringBuilderPool()
{
Builders = new StringBuilder[BuildersCount];
for (int i = 0; i < BuildersCount; i++)
{
Builders[i] = new StringBuilder(BuilderLength);
}
}
public static StringBuilder Get(out int num)
{
// Race condition here. :(
int index;
StringBuilder builder;
do
{
index = Interlocked.Increment(ref _index) % BuildersCount;
} while ((builder = Interlocked.CompareExchange(ref Builders[index], null, null)) == null);
num = index;
return builder;
}
public static void Return(int num, StringBuilder sb)
{
sb.Clear();
Builders[num] = sb;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment