Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Test project for measuring whether there would be a case for creating an optimized version of String.Format
private static int v1 = 10;
private static bool v2 = true;
private static DateTime v3 = DateTime.Now;
private static Decimal v4 = 10M;
void Main()
{
const int IterationCount = 100000;
// Warm up the JITter
Format1();
Format2();
Format3();
// Do the timings
Stopwatch sw = Stopwatch.StartNew();
for (int index = 1; index < IterationCount; index++)
Format1();
sw.Stop();
Debug.WriteLine("1: " + sw.ElapsedMilliseconds + " ms");
sw = Stopwatch.StartNew();
for (int index = 1; index < IterationCount; index++)
Format2();
sw.Stop();
Debug.WriteLine("2: " + sw.ElapsedMilliseconds + " ms");
sw = Stopwatch.StartNew();
for (int index = 1; index < IterationCount; index++)
Format3();
sw.Stop();
Debug.WriteLine("3: " + sw.ElapsedMilliseconds + " ms");
}
static void Format1()
{
string s = string.Format("abc{0}def{1}ghi{2:dd.MM.yyyy}jkl{3:c}", v1, v2, v3, v4);
GC.KeepAlive(s);
}
static void Format2()
{
string s = "abc" + v1.ToString() + "def" + v2.ToString() + "ghi" + v3.ToString("dd.MM.yyyy") + "jkl" + v4.ToString("c");
GC.KeepAlive(s);
}
static void Format3()
{
string s = new StringBuilder(30).Append("abc").Append(v1).Append("def")
.Append(v2).Append("ghi").Append(v3.ToString("dd.MM.yyyy"))
.Append("jkl").Append(v4.ToString("c")).ToString();
GC.KeepAlive(s);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.