按成员快速排序反射?

时间:2018-06-10 09:16:28

标签: c# performance list sorting reflection

关于在.Net中使用Reflection的速度,有很多警告。 为了按Datapropertyname列对datagridview进行排序,我做了一个简短的测试程序,显示Linq Sort by Reflection比Member更快。 我不确定我是否都做得正确并要求社区进行审核。

class Program {

    private static Random random = new Random();

    class TestClass {
        public string Name { get; set; }
        public int Number { get; set; }
    }


     static string RandomString(int length) {
        const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        return new string(Enumerable.Repeat(chars, length)
          .Select(s => s[random.Next(s.Length)]).ToArray());
    }


    static void SortyByReflection(List<TestClass> testlst) {
        PropertyInfo prop = typeof(TestClass).GetProperties().Where(p => p.Name == "Name").FirstOrDefault();
        List<TestClass> sorted = testlst.OrderBy(o => prop.GetValue(o)).ToList();
    }

    static void SortByMember(List<TestClass> testlst) {
        List<TestClass> sorted = testlst.OrderBy(o => o.Name).ToList();
    }


    delegate void dRunner(List<TestClass> testlst);

    static long UsedTime(dRunner testDelegate, List<TestClass> testlst) {
        Stopwatch timer = new Stopwatch();
        timer.Start();
        testDelegate(testlst);
        timer.Stop();
        return timer.ElapsedTicks;
    }

    static void Main(string[] args) {
        // make a dry run to init the program
        SortByMember(new List<TestClass>());
        SortyByReflection(new List<TestClass>());


        List<int> lstSize = new List<int> { 100, 1000, 10000, 100000 };
        foreach (int count in lstSize) {
            // Init List
            List<TestClass> testlst = new List<TestClass>();
            for (int i = 0; i < count; i++) {
                testlst.Add(new TestClass { Name = RandomString(10), Number = i });
            }
            List<long> reflection = new List<long>();
            List<long> memberTime = new List<long>();
            for (int i = 0; i < 100; i++) {
                reflection.Add(UsedTime(SortyByReflection,testlst));
                memberTime.Add(UsedTime(SortByMember,testlst));
            }
            Console.WriteLine($"{reflection.Min()} / {reflection.Max()} / {reflection.Average()} Min/ Max / Average Ticks needed for Reflection {count} size");
            Console.WriteLine($"{memberTime.Min()} / {memberTime.Max()} / {memberTime.Average()} Min/ Max / Average Ticks needed for Member {count} size");
            Console.WriteLine(new string('-', 80));
        }
        Console.WriteLine("done");
        Console.ReadLine();
    }
    /*
     * Sample output
        425 / 1837 / 539,75 Min/ Max / Average Ticks needed for Reflection 100 size
        479 / 1265 / 605,14 Min/ Max / Average Ticks needed for Member 100 size
        --------------------------------------------------------------------------------
        6251 / 11819 / 7309,82 Min/ Max / Average Ticks needed for Reflection 1000 size
        7164 / 13369 / 8201,42 Min/ Max / Average Ticks needed for Member 1000 size
        --------------------------------------------------------------------------------
        76214 / 103169 / 82003,53 Min/ Max / Average Ticks needed for Reflection 10000 size
        86139 / 121152 / 93201,55 Min/ Max / Average Ticks needed for Member 10000 size
        --------------------------------------------------------------------------------
        1092454 / 1188244 / 1139228,26 Min/ Max / Average Ticks needed for Reflection 100000 size
        1225469 / 1353753 / 1280549,37 Min/ Max / Average Ticks needed for Member 100000 size
        --------------------------------------------------------------------------------
        done
    */
}

使用Reflection时,平均值总是快10%左右。

实施新版本后(发布,在Visual Studio外部运行,使用结果和按名称更改vom按订单按订单排序,世界再次处于平衡状态。

所谓的新数字:

/*
97 / 1266 / 129,67 Min/ Max / Average Ticks needed for Reflection 100 size
19 / 265 / 28,34 Min/ Max / Average Ticks needed for Member 100 size
---------------------------------------------------------------------------
1064 / 2369 / 1357,42 Min/ Max / Average Ticks needed for Reflection 1000 size
218 / 598 / 290,43 Min/ Max / Average Ticks needed for Member 1000 size
---------------------------------------------------------------------------
12407 / 27326 / 15779,35 Min/ Max / Average Ticks needed for Reflection 10000 size
2703 / 5100 / 3366,52 Min/ Max / Average Ticks needed for Member 10000 size
---------------------------------------------------------------------------
147184 / 198677 / 160490,02 Min/ Max / Average Ticks needed for Reflection 100000 size
35333 / 45620 / 38493,46 Min/ Max / Average Ticks needed for Member 100000 size
-------------------------------------------------------------------------
*/

对于文件,这是新的源代码

  class Program {

    private static Random random = new Random();

    class TestClass {
        public string Name { get; set; }
        public int Number { get; set; }
    }


     static string RandomString(int length) {
        const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        return new string(Enumerable.Repeat(chars, length)
          .Select(s => s[random.Next(s.Length)]).ToArray());
    }


    static List<TestClass> SortyByReflection(List<TestClass> testlst) {
        PropertyInfo prop = typeof(TestClass).GetProperties().Where(p => p.Name == "Number").FirstOrDefault();
        List<TestClass> sorted = testlst.OrderBy(o => prop.GetValue(o)).ToList();
        return sorted;
    }

    static  List<TestClass> SortByMember(List<TestClass> testlst) {
        List<TestClass> sorted = testlst.OrderBy(o => o.Number).ToList();
        return sorted;
    }


    delegate List<TestClass> dRunner(List<TestClass> testlst);

    static List<TestClass> UsedTime(dRunner testDelegate, List<TestClass> testlst,out long time) {
        time = 0;
        Stopwatch timer = new Stopwatch();
        timer.Start();
        var x = testDelegate(testlst);
        timer.Stop();
        time = timer.ElapsedTicks;
        return x;
    }

    static void Main(string[] args) {


        // make a dry run to init the program
        SortByMember(new List<TestClass>());
        SortyByReflection(new List<TestClass>());


        List<int> lstSize = new List<int> { 100, 1000, 10000, 100000 };
        foreach (int count in lstSize) {
            // Init List
            List<TestClass> testlst = new List<TestClass>();
            for (int i = 0; i < count; i++) {
                testlst.Add(new TestClass { Name = RandomString(10), Number = i });
            }
            List<long> reflection = new List<long>();
            List<long> memberTime = new List<long>();
            for (int i = 0; i < 100; i++) {
                foreach (var lst in UsedTime(SortyByReflection,testlst,out long time)){
                    var tmp = lst.Name;
                    tmp += lst.Number.ToString();
                    reflection.Add(time);
                }
                foreach (var lst in UsedTime(SortByMember, testlst, out long time)) {
                    var tmp = lst.Name;
                    tmp += lst.Number.ToString();
                    memberTime.Add(time);
                }

            }
            Console.WriteLine($"{reflection.Min()} / {reflection.Max()} / {reflection.Average()} Min/ Max / Average Ticks needed for Reflection {count} size");
            Console.WriteLine($"{memberTime.Min()} / {memberTime.Max()} / {memberTime.Average()} Min/ Max / Average Ticks needed for Member {count} size");
            Console.WriteLine(new string('-', 80));
        }
        Console.WriteLine("done");
        Console.ReadLine();
    }
    /*
        97 / 1266 / 129,67 Min/ Max / Average Ticks needed for Reflection 100 size
        19 / 265 / 28,34 Min/ Max / Average Ticks needed for Member 100 size
        --------------------------------------------------------------------------------
        1064 / 2369 / 1357,42 Min/ Max / Average Ticks needed for Reflection 1000 size
        218 / 598 / 290,43 Min/ Max / Average Ticks needed for Member 1000 size
        --------------------------------------------------------------------------------
        12407 / 27326 / 15779,35 Min/ Max / Average Ticks needed for Reflection 10000 size
        2703 / 5100 / 3366,52 Min/ Max / Average Ticks needed for Member 10000 size
        --------------------------------------------------------------------------------
        147184 / 198677 / 160490,02 Min/ Max / Average Ticks needed for Reflection 100000 size
        35333 / 45620 / 38493,46 Min/ Max / Average Ticks needed for Member 100000 size
        --------------------------------------------------------------------------------
    */
}

1 个答案:

答案 0 :(得分:2)

我第一次看到这篇文章时,我并不像其他评论者那样信任它。

但在完成我自己的测试后,消除了潜在的GC和JIT影响,我可以确认声明是正确的 - SortyByReflection方法确实比SortByMember平均快。

但是,这与反射无关!

毕竟,Enumerable.OrderBy方法执行 O(N)选择器调用(即您尝试测量的反射与直接属性访问)和平均 O(N * Log2) (N)) 比较,因此时间复杂度由比较操作实现主导。

差异就是这样。反射方法使用Comparer<object>.Default,而另一种方法使用Comparer<string>.Default。令人惊讶的是,由于某种未知的原因,前者比string的后者更快。我没有测试其他数据类型(最有可能是int和其他值类型,由于第一种情况下涉及拳击,图片将是相反的),但string就是这种情况。我已经检查了比较器实现的参考源,并提供了一些可能导致它的想法,但这不属于当前问题的范围。

重要的是,OrderBy不适合测试反射与直接访问性能。如果您将第一个方法选择器更改为o => (string)prop.GetValue(o)并将第二个选择器保持原样,或者将第二个选择器更改为o => (object)o.Name并保持第一个选择器保持原样,则运行测试将显示直接访问速度比预期的反思,但由于比较时间的统治而没有那么多,特别是对于较大的N