lampac/Shared/Engine/Pools/StringBuilderPool.cs
lampac-talks f843f04fd4 chore: initial commit 154.3
Signed-off-by: lampac-talks <lampac-talks@users.noreply.github.com>
2026-01-30 16:23:09 +03:00

54 lines
1.3 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections.Concurrent;
using System.Text;
using System.Threading;
namespace Shared.Engine.Pools
{
public static class StringBuilderPool
{
static readonly ConcurrentBag<StringBuilder> _pool = new();
public static readonly StringBuilder EmptyHtml = new StringBuilder();
public static readonly StringBuilder EmptyJsonObject = new StringBuilder("{}");
public static readonly StringBuilder EmptyJsonArray = new StringBuilder("[]");
public static int rent => 32 * 1024; // 1 char == 2 byte (64кб, ниже LOH лимита ~85кб)
public static int FreeCont => _pool.Count;
public static int RentNew;
public static int GC;
public static StringBuilder Rent()
{
if (_pool.TryTake(out var sb))
return sb;
Interlocked.Increment(ref RentNew);
return new StringBuilder(rent);
}
public static void Return(StringBuilder sb)
{
if (sb == null)
return;
if (sb.Capacity > PoolInvk.rentCharMax || _pool.Count >= 5)
{
Interlocked.Increment(ref GC);
}
else if (sb.Capacity >= rent)
{
sb.Clear();
_pool.Add(sb);
}
}
}
}