一次 string的 GC 探寻
public class PlayText : MonoBehaviour {
Text txt;
string story;
StringBuilder sb;
void Awake()
{
txt = GetComponent<Text>();
story = txt.text;
txt.text = "";
sb = new StringBuilder();
// TODO: add optional delay when to start
Profiler.BeginSample("playTest");
StartCoroutine(PlayText1());
Profiler.EndSample();
}
IEnumerator PlayText1()
{
foreach (char c in story)
{
sb.Append(c);
1 txt.text = sb.ToString();
2 txt.text += c;
yield return new WaitForSeconds(0.025f);
}
Text txt;
string story;
StringBuilder sb;
void Awake()
{
txt = GetComponent<Text>();
story = txt.text;
txt.text = "";
sb = new StringBuilder();
// TODO: add optional delay when to start
Profiler.BeginSample("playTest");
StartCoroutine(PlayText1());
Profiler.EndSample();
}
IEnumerator PlayText1()
{
foreach (char c in story)
{
sb.Append(c);
1 txt.text = sb.ToString();
2 txt.text += c;
yield return new WaitForSeconds(0.025f);
}
}
为了在unity做出一个连续打字的效果,由于c#中字符串具有不变性,于是使用stringbuilder来 优化字符串的拼接,但是怀疑在 startcrountine中每次都要 使用stringBguilder.ToString()也会不断的产生出GC,于是使用 profiler来探寻一下。
使用 1 注釋掉2的時候 ,发现随着游戏的进行gc不断的增加.最多的时候 到250B(实验3次得到同样结果)主要在于 string.internalAllocateStr()产生了230B
使用2注释了1的时候
最多也只是196b(实验了3次),少了44B。由此可见stringBuilder.toString()产生的gc高于string字符串本身