Using RedGate Profiler Using the Following Code
class Program { static string data = ""; static Dictionary<string, string> values; static void Main(string[] args) { Console.WriteLine("Data length: " + data.Length); values = new Dictionary<string, string>() { { "ab", "aa" }, { "jk", "jj" }, { "lm", "ll" }, { "yz", "zz" }, { "ef", "ff" }, { "st", "uu" }, { "op", "pp" }, { "x", "y" } }; StringReplace(data); StringBuilderReplace1(data); StringBuilderReplace2(new StringBuilder(data, data.Length * 2)); Console.ReadKey(); } private static void StringReplace(string data) { foreach(string k in values.Keys) { data = data.Replace(k, values[k]); } } private static void StringBuilderReplace1(string data) { StringBuilder sb = new StringBuilder(data, data.Length * 2); foreach (string k in values.Keys) { sb.Replace(k, values[k]); } } private static void StringBuilderReplace2(StringBuilder data) { foreach (string k in values.Keys) { data.Replace(k, values[k]); } } }
- String.Replace = 5.843ms
- StringBuilder.Replace # 1 = 4.059ms
- Stringbuilder.Replace # 2 = 0.461ms
String Length = 1456
stringbuilder # 1 creates a string constructor in a method, and # 2 doesn’t make the difference in performance the same, most likely, since you are simply moving this work out of the method. If you start with stringbuilder instead of a string, then instead of # 2 it may be instead.
As for the memory using the RedGateMemory profiler, you have nothing to worry about until you go into MANY replacement operations in which the builder will build as a whole.
Dustin Davis Jun 29 '11 at 17:40 2011-06-29 17:40
source share