Friday, July 27, 2012

[C#] Randomize Sort String Array

RandomStringArray

今天在看code的時候,發現一段看起來可以改善效能,於是就來試一下。這段程式是要把一個字串陣列作亂數排序,原本是自己去Sort,我改用LINQ幫我做Sort,測試之後速度快了五倍多,可說是飛快,下面是程式部分。



        static void Main(string[] args)
        {
            Process proc = Process.GetCurrentProcess();
            Console.WriteLine("Random by Old Way");
            TimeSpan sTime=proc.TotalProcessorTime;
            for (int i = 0; i < 10000; i++)
            {
                RandomString(100);
            }
            Console.WriteLine(proc.TotalProcessorTime-sTime);
            Console.WriteLine();
            foreach (var s in RandomString(10))
            {
                Console.Write(s);
            }
            Console.ReadLine();
        }

        public static String[] RandomString(int length)
        {
            String[] index = new String[length];
            for (int i = 0; i < index.Length; i++)
            {
                index[i] = i.ToString(CultureInfo.InvariantCulture);
            }
            return RandomizeSort(index);
        }

        public static String[] RandomizeSort(String[] input)
        {
            //Old way
            for (int t = 0; t < input.Length; t++)
            {
                String tmp = input[t];
                int r = new Random().Next(t, input.Length);
                input[t] = input[r];
                input[r] = tmp;
            }
            return input;

            //LINQ
            //return input.OrderBy(x=>Guid.NewGuid()).ToArray();
        }

我每次測試都用大小為100的字串陣列,跑10000次,兩種方式各測試五次的結果平均起來
Old way : 4.88907134 sec
LINQ : 0.86424554 sec
LINQ的速度是原本方式的 17.68% ,可說是進步不少。

可賀可喜,收工。

1 comment:

  1. Rolex offers a wide range of models from professional to uk replica rolex classic watches to fit any wrist. fake sea dweller watches Choose your favorite model, material, bezel, dial and bracelet, explore the Rolex collection and find the watch that's right for you.

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...