წინა პოსტის შემდეგ დავინტერესდი რომელი მეთოდი არის ყველაზე წარმადი, დავწერე პატარა ტესტი, აღმოჩნდა რომ მაინც და მაინც უპირატესობა არც ერთ არ გააჩნია. "გამარჯვებული" მეთოდი იცვლება ტესტის რამდენჯერმე შესრულებისას.
class Program
{
delegate bool CDelegate(string text, List<string> phrases);
static bool C1(string text, List<string> word)
{
foreach (string phrase in word)
{
if (text.Contains(phrase))
return true;
}
return false;
}
static bool C2(string text, List<string> word)
{
return word.Any(phrase => text.Contains(phrase));
}
static bool C3(string text, List<string> word)
{
return word.Any(text.Contains);
}
static long TestMethod(CDelegate method)
{
List<string> words = new List<string>();
for (int i = 0; i < 10000; i++)
{
words.Add(i.ToString("0000"));
}
Stopwatch stopwatch = new Stopwatch();
long time = 0;
int dummy = 0;
stopwatch.Start();
for (int j = 0; j < 1000; j++)
{
//string str = "a long text with a number in the end:" + (j % 2 == 0 ? "0009" : ""); // Fast find
//string str = "a long text with a number in the end:" + (j % 2 == 0 ? "9990" : ""); // Slow find
string str = "a long text with a number in the end:" + (j % 2 == 0 ? j.ToString("0000") : ""); // Smooth distribution
if (C1(str, words))
dummy++;
}
stopwatch.Stop();
time += stopwatch.ElapsedTicks;
Console.WriteLine("{0} {1} [{2}]", ((((method)).Method)).Name, time, dummy);
return time;
}
static void Main(string[] args)
{
SortedDictionary<long, string> sorted = new SortedDictionary<long, string>();
sorted.Add(TestMethod(C1), "C1");
sorted.Add(TestMethod(C2), "C2");
sorted.Add(TestMethod(C3), "C3");
Console.WriteLine("Winner is {0}", sorted.Values.ToArray()[0]);
}
}
65bf6049-84ad-4315-8845-020bafbfd2c7|1|5.0
Tags: