Created
October 5, 2015 23:10
-
-
Save Belorus/079a4ffabcadb464ad11 to your computer and use it in GitHub Desktop.
StringBuilder pool C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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