// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Text; using System.Text.RegularExpressions; namespace E { public class MainClass { private const int N = 100000000; private const string FMT = "{0,-25} : {1} -> {2} x {3} : {4}"; private static void TestStringReplace(string s) { int n = N / s.Length; string s2 = null; DateTime dt1 = DateTime.Now; for(int i = 0; i < n; i++) { s2 = s.Replace("\r", "").Replace("\n", "").Replace("\t", ""); } DateTime dt2 = DateTime.Now; Console.WriteLine(String.Format(FMT, "String Replace", s.Length, s2.Length, n, (dt2 - dt1).TotalSeconds)); } private static void TestStringBuilderReplace(string s) { int n = N / s.Length; StringBuilder sb = new StringBuilder(s); string s2 = null; DateTime dt1 = DateTime.Now; for(int i = 0; i < n; i++) { s2 = sb.Replace("\r", "").Replace("\n", "").Replace("\t", "").ToString(); } DateTime dt2 = DateTime.Now; Console.WriteLine(String.Format(FMT, "StringBuilder Replace", s.Length, s2.Length, n, (dt2 - dt1).TotalSeconds)); } private static void TestRegexReplace(string s) { int n = N / s.Length; string s2 = null; DateTime dt1 = DateTime.Now; for(int i = 0; i < n; i++) { s2 = Regex.Replace(s, "[\r\n\t]", ""); } DateTime dt2 = DateTime.Now; Console.WriteLine(String.Format(FMT, "Regex Replace", s.Length, s2.Length, n, (dt2 - dt1).TotalSeconds)); } private static void TestRegexReplaceOptimized(string s) { int n = N / s.Length; Regex re = new Regex("[\r\n\t]", RegexOptions.Compiled); string s2 = null; DateTime dt1 = DateTime.Now; for(int i = 0; i < n; i++) { s2 = re.Replace(s, ""); } DateTime dt2 = DateTime.Now; Console.WriteLine(String.Format(FMT, "Regex Replace Optimized", s.Length, s2.Length, n, (dt2 - dt1).TotalSeconds)); } private static void Test(string s) { TestStringReplace(s); TestStringBuilderReplace(s); TestRegexReplace(s); TestRegexReplaceOptimized(s); } public static void Main(string[] args) { string shortstr = "aaa\rbbb\nccc\tddd"; Test(shortstr); string longstr = shortstr; longstr += longstr; longstr += longstr; longstr += longstr; longstr += longstr; longstr += longstr; longstr += longstr; Test(longstr); string nonestr = String.Empty.PadRight(1000, 'A'); Test(nonestr); } } }