比较两个对象属性的最快方法

时间:2012-11-29 17:25:23

标签: c# .net reflection

有人建议使用反射。我的方法效果很好,但是超过800,000次迭代,我得出了一个明显的结论(大多数已经发现)反射只是没有削减它。

这是我的助手课程的一部分:

public static class Helper
{

    public static string[] ignoredProperties = { "EntityState", 
                                                    "EntityKey", 
                                                    "Prop1", 
                                                    "Prop2", 
                                                    "Whatever", 

                                               };

    /// <summary>
    /// Check if properties of two objects are the same. Bypasses specified properties.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="first"></param>
    /// <param name="other"></param>
    /// <param name="ignoreProperties"></param>
    /// <returns></returns>
    public static bool PropertiesEquals<T>(this T first, T other, string[] ignoreProperties)
    {
        var propertyInfos = first.GetType().GetProperties();
        foreach (PropertyInfo propertyInfo in propertyInfos)
        {
            //Faster with custom method ? Nah...
            //if (FindElementIndex(ignoreProperties, propertyInfo.Name) < 0)
            //Probably faster if hardcoded.... Nah, not really either...
            //if (propertyInfo.Name != "EntityKey" && propertyInfo.Name != "EntityState" && propertyInfo.Name != "Group_ID" && propertyInfo.Name != "Import_status")
            if (Array.IndexOf(ignoreProperties, propertyInfo.Name) < 0)
                if (!Equals(propertyInfo.GetValue(first, null), propertyInfo.GetValue(other, null)))
                    return false;
        }
        return true;
    }

    public static int FindElementIndex(string[] input, string value)
    {
        int arraySize = input.Length - 1;
        Type valueType = value.GetType();

        for (int x = 0; x <= arraySize; x++)
        {
            if (input[x] == value)
                return x;
        }

        return -1;
    }

问题是这些对象取决于类型,最多可以检查50个属性。呃...所以我真的不能做一堆if ifs。

有什么方法可以加快这一点吗?

感谢。

3 个答案:

答案 0 :(得分:2)

您可以使用Reflection.Emit动态创建比较方法,然后只需运行它即可。代码将被JIT编辑并且运行得相当快。

有一个缺点 - 你必须知道IL是如何工作的。

答案 1 :(得分:1)

  

有什么方法可以加快这一点吗?

绝对。如果您要为不同的对象多次获取相同的属性,请为每个属性创建一个委托(请参阅我之前写的this blog post的一些示例)或使用像Hyperdescriptor这样的项目。 / p>

(从.NET 3.5开始,另一种创建委托的方法是使用表达式树并编译它们。)

答案 2 :(得分:0)

您可以构建 Expression ,指定应比较哪些属性。然后,您可以将其编译为lambda表达式,并使用它将项目与委托调用的性能进行比较。