// 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.RegularExpressions; namespace E { public abstract class Test { private const int N = 1000000; private string name; public Test(string name) { this.name = name; } public abstract int CountChar(string s, char c); public void DoTest() { int nc = 0; long t1 = DateTime.Now.Ticks; for(int i = 0; i < N; i++) { nc = CountChar("Dette er en test", 'e'); } long t2 = DateTime.Now.Ticks; Console.WriteLine(String.Format("{0,-15} : {1,10} ({2})", name, (t2 - t1), nc)); } } public class TestForLoop : Test { public TestForLoop() : base("for loop") { } public override int CountChar(string s, char c) { int res = 0; for(int i = 0; i < s.Length; i++) { if(s[i] == c) { res++; } } return res; } } public class TestSplit : Test { public TestSplit() : base("Split") { } public override int CountChar(string s, char c) { return (s.Split(c).Length - 1); } } public class TestRegex : Test { public TestRegex() : base("Regex") { } public override int CountChar(string s, char c) { Regex r = new Regex("" + c); return r.Matches(s).Count; } } public class TestRegexFixed : Test { private static Regex r = new Regex("e", RegexOptions.Compiled); public TestRegexFixed() : base("Regex fixed") { } public override int CountChar(string s, char c) { return r.Matches(s).Count; } } public class TestClass { public static void Main(string[] args) { (new TestForLoop()).DoTest(); (new TestSplit()).DoTest(); (new TestRegex()).DoTest(); (new TestRegexFixed()).DoTest(); } } }