Skip to content

Instantly share code, notes, and snippets.

@sarbian
Created April 13, 2016 19:36
Show Gist options
  • Save sarbian/9048da8ed684fa411a6a598f6c0670db to your computer and use it in GitHub Desktop.
Save sarbian/9048da8ed684fa411a6a598f6c0670db to your computer and use it in GitHub Desktop.
void Update()
{
int count = 1000;
string format = "|{0} {1}|";
Profiler.BeginSample("ToString");
for (int i = 0; i < count; i++)
{
text1.text = i.ToString() + " " + i.ToString();
}
Profiler.EndSample();
Profiler.BeginSample("Concat");
for (int i = 0; i < count; i++)
{
text1.text = string.Concat(i, " ", i);
}
Profiler.EndSample();
// The StringBuilder creation is in the loop on purpose for those
Profiler.BeginSample("StringBuilderNew");
for (int i = 0; i < count; i++)
{
StringBuilder sbl = new StringBuilder();
sbl.AppendFormat(format, i, i);
text1.text = sbl.ToString();
}
Profiler.EndSample();
Profiler.BeginSample("ConcatFormatNew");
for (int i = 0; i < count; i++)
{
StringBuilder sbl = new StringBuilder();
sbl.ConcatFormat(format, i, i);
text1.text = sbl.ToString();
}
Profiler.EndSample();
StringBuilder sbr = new StringBuilder();
Profiler.BeginSample("StringBuilderReuse");
for (int i = 0; i < count; i++)
{
sbr.AppendFormat(format, i, i);
text1.text = sbr.ToString();
sbr.Length = 0;
}
Profiler.EndSample();
sbr.Length = 0;
Profiler.BeginSample("ConcatFormatReuse");
for (int i = 0; i < count; i++)
{
sbr.ConcatFormat(format, i, i);
text1.text = sbr.ToString();
sbr.Length = 0;
}
Profiler.EndSample();
Profiler.BeginSample("StringBuilderCache");
for (int i = 0; i < count; i++)
{
StringBuilder sb = StringBuilderCache.Acquire();
sb.AppendFormat(format, i, i);
text2.text = sb.GetGCFreeStringAndRelease();
}
Profiler.EndSample();
Profiler.BeginSample("StringBuilderCache-ConcatFormat");
for (int i = 0; i < count; i++)
{
StringBuilder sb = StringBuilderCache.Acquire();
sb.ConcatFormat(format, i, i);
text3.text = sb.GetGCFreeStringAndRelease();
}
Profiler.EndSample();
}
@sarbian
Copy link
Author

sarbian commented Apr 13, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment