Test project for measuring whether there would be a case for creating an optimized version of String.Format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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