共享StringBuilder 可以使用在一些临时需要拼接字符串的场合 避免重复创建StringBuilder实例
允许一定程度的嵌套 ,默认8层
优点 减少重复创建 避免直接使用String导致的大量GC
应用时注意 牵扯到长时间引用的string不能用这个 又因为默认了8层 导致 如果使用了 也有可能因为instanceid未被重置的原因导致很难被发现这个错误 这是危险的
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
public class SharedStringBuilder
{
private const int MAX_INSTANCE = 8;
private const int DEFAULE_CAPACITY = 256;
public static StringBuilder Instance {
get
{
if (s_instance == null)
{
s_instance = new StringBuilder[MAX_INSTANCE];
s_instanceId = 0;
}
StringBuilder instance = s_instance[s_instanceId];
if (instance == null)
{
instance = new StringBuilder(DEFAULE_CAPACITY);
s_instance[s_instanceId] = instance;
}
instance.Length = 0;
s_instanceId++;
if (s_instanceId >= MAX_INSTANCE)
{
s_instanceId = 0;
}
return instance;
}
}
private static int s_instanceId;
private static StringBuilder[] s_instance;
}