Created
July 30, 2014 11:27
-
-
Save PatrickMcDonald/81026b2d715559171ca7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
namespace StringTimes | |
{ | |
using System; | |
public class Program | |
{ | |
private static void Main(string[] args) | |
{ | |
const int Iterations = 10000000; | |
string Icon = "<i class=\"fa fa-bolt red\"></i>"; | |
string Risk = "Critical"; | |
Time(Iterations, "string.Format", () => | |
{ | |
string s = string.Format("{0} {1}", Icon, Risk); | |
}); | |
Time(Iterations, "concatenation", () => | |
{ | |
string s = Icon + " " + Risk; | |
}); | |
Time(Iterations, "StringBuilder", () => | |
{ | |
var sb = new System.Text.StringBuilder(); | |
sb.Append(Icon); | |
sb.Append(" "); | |
sb.Append(Risk); | |
string s = sb.ToString(); | |
}); | |
Console.Write("Press any key to continue . . ."); | |
Console.ReadKey(true); | |
} | |
private static void Time(int iterations, string method, Action action) | |
{ | |
System.Console.WriteLine("Timing {0} iterations of {1}", iterations, method); | |
var sw = System.Diagnostics.Stopwatch.StartNew(); | |
for (int i = 0; i < iterations; i++) | |
{ | |
action.Invoke(); | |
} | |
GC.Collect(); | |
GC.Collect(); | |
var elapsed = sw.Elapsed; | |
Console.WriteLine("{0} took {1}", method, elapsed); | |
Console.WriteLine(); | |
} | |
} | |
} | |
/* | |
Timing 10000000 iterations of string.Format | |
string.Format took 00:00:05.5955579 | |
Timing 10000000 iterations of concatenation | |
concatenation took 00:00:01.5413132 | |
Timing 10000000 iterations of StringBuilder | |
StringBuilder took 00:00:06.7475308 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment