პატარა ტესტი

By George Khubua at April 27, 2010 00:03
Filed Under: .NET

წინა პოსტის შემდეგ დავინტერესდი რომელი მეთოდი არის ყველაზე წარმადი, დავწერე პატარა ტესტი, აღმოჩნდა რომ მაინც და მაინც უპირატესობა არც ერთ არ გააჩნია. "გამარჯვებული" მეთოდი იცვლება ტესტის რამდენჯერმე შესრულებისას.

 

    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]);
            
        }
    }
Comments are closed

ავტორის შესახებ

გიორგი ხუბუა - .NET პლატფორმაზე დეველოპმენტის 5-წელიწადზე მეტი გამოცდილება

ჯერ ვლაგდებით :)

მასალა სკრამის შესახებ იწერება და სულ მალე იქნება

დარჩით ჩვენთან ერთად, არ გადართოთ Smile

მეგობარი ბლოგები

http://www.gode.ge/ - ძალზედ შინაარსიანი ბლოგი